Node.js Reference ยท Streams and readline
Node.js writable.write() method
Reference for writable.write() in Node.js: the boolean return value, the drain event, write callbacks, encodings, errors after end and object mode.
writable.write(chunk[, encoding][, callback]) sends data to a writable stream. It does not wait for the data to be flushed: the chunk goes into an internal buffer, and the return value tells you whether you may keep writing.
When write() returns false, the buffer has reached highWaterMark. Data is not lost, but you should stop writing until the stream emits 'drain'. Respecting that signal is how you keep memory flat when the producer is faster than the destination.
const ok = writable.write("some text"); if (!ok) await once(writable, "drain");
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.write(chunk[, encoding][, callback]): boolean
| Name | Description |
|---|---|
chunk |
string, Buffer, TypedArray or DataView for byte streams; any value except null in object mode. |
encoding |
Encoding used when chunk is a string. Defaults to 'utf8' or the value set with setDefaultEncoding(). Ignored for buffers. |
callback |
Called when this chunk has been flushed, or with an error if it failed. |
Returns: true if you may write more, false if the internal buffer is at or over highWaterMark.
Errors: writing after end() emits ERR_STREAM_WRITE_AFTER_END (via 'error' and the callback). Writing null throws ERR_STREAM_NULL_VALUES. Invalid chunk types throw ERR_INVALID_ARG_TYPE. Writing to a destroyed stream reports ERR_STREAM_DESTROYED.
Usage notes
- A
falsereturn does not reject the chunk: it was accepted. Ignoring it works but lets memory grow without bound. 'drain'fires once, after the buffer has emptied following afalsereturn.writableNeedDraintells you whether a drain is pending.- The callback receives an error only when this particular write failed. The same error is also emitted as
'error', so listen for it. - Strings are converted to buffers on write (unless
decodeStringsisfalse). Writing many tiny strings is slow; batch them or usecork(). process.stdout.write()is a normal writable; for pipes it may be asynchronous, so callprocess.exit()carefully.- Use
stream.pipeline()orpipe()when moving data from a readable, so backpressure is applied for you. writable.writableLengthreports buffered bytes (or objects), andwritableHighWaterMarkthe threshold.