Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Duplex destroy #2831

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/stream/lib/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
28 changes: 28 additions & 0 deletions packages/stream/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ export class SerialPortStream<T extends BindingInterface = BindingInterface> 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)
}
Expand Down Expand Up @@ -473,6 +477,30 @@ export class SerialPortStream<T extends BindingInterface = BindingInterface> 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)
}
}
}

/**
Expand Down
Loading