Skip to content

Instantly share code, notes, and snippets.

@matianfu
Last active May 6, 2020 08:48
Show Gist options
  • Save matianfu/39127d0ddd99d8fb2b1c15592bd4b8b4 to your computer and use it in GitHub Desktop.
Save matianfu/39127d0ddd99d8fb2b1c15592bd4b8b4 to your computer and use it in GitHub Desktop.
Execution sequence of node stream.Writable during destroy
const hello = new require('stream').Writable({
destroy (err, callback) {
console.log('2 before callback in _destroy')
callback(err)
console.log('3 after callback in _destory')
}
}).on('error', err => console.log('6 error'))
.on('close', () => console.log('7 close'))
console.log('1 before destroy')
process.nextTick(() => console.log('5 before destroy nextTicked'))
hello.destroy(new Error('some error'))
console.log('4 after destroy')
process.nextTick(() => console.log('8 after destroy nextTicked'))
/**
* ```
* $ node test.js
* 1 before destroy
* 2 before callback in _destroy
* 3 after callback in _destory
* 4 after destroy
* 5 before destroy nextTicked
* 6 error
* 7 close
* 8 after destroy nextTicked
* ```
*
* The output shows that:
* 1. the internal _destroy is triggered synchronously with destroy.
* 2. error and close are emitted via nextTick.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment