Node.js Reference ยท Streams and readline
Node.js writable.end() method
Reference for writable.end() in Node.js: write a last chunk, signal that no more data comes, the finish event, callbacks and what happens on repeat calls.
writable.end([chunk[, encoding]][, callback]) tells a writable stream that you are done. An optional last chunk is written first. Once all buffered data has been flushed, the stream emits 'finish', then (with the default autoDestroy) 'close'.
Always end streams you write to, otherwise the other side (a file, a socket, a downstream reader) may wait forever. end() does not close the stream immediately: wait for 'finish' or the callback before assuming the data has been handled.
writable.end("last words");
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
writable.end([chunk[, encoding]][, callback]): this
| Name | Description |
|---|---|
chunk |
Optional last data, same types as in write(). |
encoding |
Encoding for a string chunk. |
callback |
Added as a listener for 'finish'. If the stream errors, it receives the error instead. |
Returns: the stream.
Edge cases: calling end() again after the stream has ended is allowed only without a chunk; with a chunk it reports ERR_STREAM_WRITE_AFTER_END. Related flags: writableEnded becomes true immediately after end(); writableFinished becomes true only when 'finish' is emitted.
Usage notes
- Event order is: all writes complete,
final()runs (if defined),'finish', then'close'. - Implement
final(callback)(or_final) in a custom writable to flush internal state, such as a trailing record or a footer, before'finish'. - Ending a file stream closes the file descriptor automatically after
'finish'. - When a readable is piped into a writable,
pipe()callsend()for you when the source ends (unless{ end: false }). process.stdoutandprocess.stderrcannot be ended.- On HTTP,
response.end()is the same idea but sends the final chunk and marks the message complete. end()with a pending backpressure state is fine; buffered data is still flushed.