Skip to content

Commit cf2a71b

Browse files
authored
feat: Implement Duplex destroy (#2831)
* Implement Duplex destroy * Add some tests
1 parent 9966d46 commit cf2a71b

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

packages/stream/lib/index.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -792,6 +792,26 @@ describe('SerialPort', () => {
792792
})
793793
})
794794
})
795+
796+
describe('#destroy', () => {
797+
it('calls close', done => {
798+
const port = new SerialPortStream(openOpts)
799+
port.on('close', () => done())
800+
port.destroy()
801+
})
802+
803+
it("doesn't open after destroy", done => {
804+
const port = new SerialPortStream(openOpts)
805+
port.on('open', () => {
806+
port.destroy()
807+
assert.isTrue(port.destroyed)
808+
port.open(err => {
809+
assert.instanceOf(err, Error)
810+
done()
811+
})
812+
})
813+
})
814+
})
795815
})
796816

797817
describe('reading data', () => {

packages/stream/lib/index.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,10 @@ export class SerialPortStream<T extends BindingInterface = BindingInterface> ext
148148
* @emits open
149149
*/
150150
open(openCallback?: ErrorCallback): void {
151+
if (this.destroyed) {
152+
return this._asyncError(new Error('Port is already destroyed - it cannot be reopened'), openCallback)
153+
}
154+
151155
if (this.isOpen) {
152156
return this._asyncError(new Error('Port is already open'), openCallback)
153157
}
@@ -473,6 +477,30 @@ export class SerialPortStream<T extends BindingInterface = BindingInterface> ext
473477
},
474478
)
475479
}
480+
481+
/**
482+
* Implementation for Duplex._destroy. Disposes of underlying resources and forbids this port from being reopened
483+
* @param err
484+
* @param callback
485+
*/
486+
_destroy(err: Error | null, callback: ErrorCallback) {
487+
debug('_destroy')
488+
if (this.port) {
489+
debug('_destroy', 'releasing port')
490+
this.port.close().then(
491+
() => {
492+
callback(err)
493+
},
494+
e => {
495+
callback(e)
496+
},
497+
)
498+
this.port = undefined
499+
} else {
500+
debug('_destroy', 'nothing to do; port has not been opened')
501+
callback(err)
502+
}
503+
}
476504
}
477505

478506
/**

0 commit comments

Comments
 (0)