diff --git a/packages/stream/lib/index.test.ts b/packages/stream/lib/index.test.ts index 01201b53f..c221208a5 100644 --- a/packages/stream/lib/index.test.ts +++ b/packages/stream/lib/index.test.ts @@ -791,6 +791,26 @@ describe('SerialPort', () => { }) }) }) + + describe('#destroy', () => { + it('calls close', done => { + const port = new SerialPortStream(openOpts) + port.on('close', () => done()) + port.destroy() + }) + + it("doesn't open after destroy", done => { + const port = new SerialPortStream(openOpts) + port.on('open', () => { + port.destroy() + assert.isTrue(port.destroyed) + port.open(err => { + assert.instanceOf(err, Error) + done() + }) + }) + }) + }) }) describe('reading data', () => { diff --git a/packages/stream/lib/index.ts b/packages/stream/lib/index.ts index 6272499c2..9262beff0 100644 --- a/packages/stream/lib/index.ts +++ b/packages/stream/lib/index.ts @@ -148,6 +148,10 @@ export class SerialPortStream ext * @emits open */ open(openCallback?: ErrorCallback): void { + if (this.destroyed) { + return this._asyncError(new Error('Port is already destroyed - it cannot be reopened'), openCallback) + } + if (this.isOpen) { return this._asyncError(new Error('Port is already open'), openCallback) } @@ -473,6 +477,30 @@ export class SerialPortStream ext }, ) } + + /** + * Implementation for Duplex._destroy. Disposes of underlying resources and forbids this port from being reopened + * @param err + * @param callback + */ + _destroy(err: Error | null, callback: ErrorCallback) { + debug('_destroy') + if (this.port) { + debug('_destroy', 'releasing port') + this.port.close().then( + () => { + callback(err) + }, + e => { + callback(e) + }, + ) + this.port = undefined + } else { + debug('_destroy', 'nothing to do; port has not been opened') + callback(err) + } + } } /**