Node.js Reference ยท Streams and readline
Node.js readable.setEncoding() method
Reference for readable.setEncoding() in Node.js: receive strings instead of Buffers, handle multi-byte characters across chunks and choose an encoding.
readable.setEncoding(encoding) makes a readable stream deliver strings instead of Buffer objects. The stream decodes the bytes with a StringDecoder, so a multi-byte character that is split between two chunks still comes out whole. Decoding chunks yourself with chunk.toString() does not give that guarantee.
stream.setEncoding("utf8"); stream.on("data", (text) => { /* a string */ });
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.setEncoding(encoding): this
| Name | Description |
|---|---|
encoding |
A string encoding: 'utf8', 'utf16le', 'latin1', 'ascii', 'base64', 'base64url', 'hex' and so on. |
Returns: the stream. The readableEncoding property reports the current setting (null when none).
Edge cases: the option encoding in the constructor or in fs.createReadStream(path, { encoding }) does the same thing. Switching encoding after data has already been buffered re-decodes the buffered chunks.
Usage notes
- With an encoding set,
'data'events,read()and async iteration produce strings. Without it they produceBuffers (or arbitrary values in object mode). - With
'utf8', an incomplete trailing sequence is held back until the next chunk arrives. At the end, any leftover bytes become the replacement character U+FFFD. 'hex'and'base64'also work for binary data you want as text, such as hashes.- Calling
chunk.toString()per chunk breaks characters at chunk boundaries. Either callsetEncoding(), or collect all buffers and decode once withBuffer.concat(chunks).toString(). setEncoding()has no effect on writable streams; usewritable.setDefaultEncoding()for string writes.