Skip to content

Commit

Permalink
feat: add optional end event for piping (#1926)
Browse files Browse the repository at this point in the history
This will allow streams to end. We haven't done this because it allows a stream to be reopened and data to be continued to be read. 

Adds `endOnClose` to stream options so the stream will emit the end event when the port is closed. This will signal any piped parsers to end as well. If the port is reopened the parsers won’t function.
  • Loading branch information
reconbot committed Sep 22, 2019
1 parent eae28d4 commit 275315a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 4 additions & 0 deletions packages/stream/stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const FLOWCONTROLS = Object.freeze(['xon', 'xoff', 'xany', 'rtscts'])

const defaultSettings = Object.freeze({
autoOpen: true,
endOnClose: false,
baudRate: 9600,
dataBits: 8,
hupcl: true,
Expand Down Expand Up @@ -432,6 +433,9 @@ SerialPort.prototype.close = function(callback, disconnectError) {
this.closing = false
debug('binding.close', 'finished')
this.emit('close', disconnectError)
if (this.settings.endOnClose) {
this.emit('end')
}
if (callback) {
callback.call(this, disconnectError)
}
Expand Down
23 changes: 22 additions & 1 deletion packages/stream/stream.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ describe('SerialPort', () => {
})

describe('#close', () => {
it('emits a close event', done => {
it('emits a close event for writing consumers', done => {
const port = new SerialPort('/dev/exists', () => {
port.on('close', () => {
assert.isFalse(port.isOpen)
Expand All @@ -449,6 +449,27 @@ describe('SerialPort', () => {
})
})

it('emits an "end" event for reading consumers when endOnClose is true', done => {
const port = new SerialPort('/dev/exists', { endOnClose: true })
port.on('open', () => {
port.on('end', () => {
assert.isFalse(port.isOpen)
done()
})
port.close()
})
})

it('doesn\'t emit an "end" event for reading consumers when endOnClose is false', done => {
const port = new SerialPort('/dev/exists')
port.on('open', () => {
port.on('end', () => {
done(new Error('Should not have ended'))
})
port.close(() => done())
})
})

it('has a close callback', done => {
const port = new SerialPort('/dev/exists', () => {
port.close(() => {
Expand Down

0 comments on commit 275315a

Please sign in to comment.