string_decoder
The string_decoder
module provides a way to decode Buffer
objects into strings without breaking multibyte characters. Useful when streaming text data.
API Surface
Class: StringDecoder
new StringDecoder([encoding])
— defaultutf8
..write(buffer)
— returns string decoded from buffer..end([buffer])
— flush remaining input and end decoding.
Supported encodings: utf8
, utf16le
, base64
.
Examples (English only)
const { StringDecoder } = require("string_decoder");
const decoder = new StringDecoder("utf8");
const buf1 = Buffer.from([0xe0, 0xa4, 0xa8]); // incomplete UTF-8 char
const buf2 = Buffer.from([0xa6]);
console.log(decoder.write(buf1)); // empty, waiting for completion
console.log(decoder.write(buf2)); // outputs proper char (e.g., 'न')
// End flush
console.log(decoder.end());
Notes
- Unlike
buf.toString()
, StringDecoder preserves whole characters across chunk boundaries. - Useful when reading text from streams in arbitrary-sized chunks.
- Always call
.end()
at the end of input to flush buffered bytes.