Node.js Reference ยท Streams and readline
Node.js readable.destroy() method
Reference for readable.destroy([error]) in Node.js: release a stream's resources immediately, emit error and close, and implement _destroy for cleanup.
readable.destroy([error]) ends a stream immediately and releases its resources, such as a file descriptor or socket. Unlike a normal end, buffered data is discarded. If you pass an error, the stream emits 'error' with it and then 'close'; without an error it only emits 'close'.
The same method exists on every stream type, and the destroyed property tells you whether it has run. Destroying is the correct way to stop reading early, for example when a client disconnects.
stream.destroy(); // quiet shutdown stream.destroy(new Error("abort")); // shutdown with 'error'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
readable.destroy([error]): this readable.destroyed: boolean readable.closed: boolean
| Name | Description |
|---|---|
error |
Optional. If given, it is emitted as 'error' (on the next tick) after cleanup. |
Returns: the stream. Calling destroy() again is harmless: the first call wins and later errors are ignored.
Implementing cleanup: pass a destroy(error, callback) option to the constructor or override _destroy(error, callback). Close your resources there and call callback(error) when finished.
Usage notes
- After
destroy(),read()returns nothing and writes to a duplex fail withERR_STREAM_DESTROYED.'end'is not emitted. 'close'is the signal that all resources are released. It is always emitted last (unlessemitClose: falsewas passed).- An error passed to
destroy()with no'error'listener becomes an uncaught exception, so attach a listener first. readable.closedistrueafter'close', whiledestroyedistrueas soon asdestroy()is called.stream.pipeline()destroys all streams on failure. With barepipe()you must destroy them yourself.- With
autoDestroy: true(the default), a stream destroys itself after'end'(readable) or'finish'(writable), so you rarely need to call it after a successful finish. - Do not override
destroy()itself in subclasses; implement_destroy().