The StringDecoder Module in Node.js

The node:string_decoder module provides a safe and reliable way to decode Buffer objects into strings, especially when dealing with multibyte UTF‑8 or UTF‑16 characters. Unlike buffer.toString(), which may produce corrupted output when characters are split across chunks, StringDecoder preserves incomplete multibyte sequences and completes them only when enough bytes are available.

UTF‑8 / UTF‑16 multibyteBuffer decodingIncomplete characters handlingstringDecoder.write()stringDecoder.end()

~2 min read · Updated Dec 30, 2025

1. Introduction


The node:string_decoder module is designed to convert Buffer data into strings without breaking multibyte characters. It is especially useful when processing streamed or chunked data where character boundaries may not align with chunk boundaries.


2. Accessing the Module


const { StringDecoder } = require('node:string_decoder');

3. Basic Usage


Here is a simple example decoding UTF‑8 multibyte characters:


const decoder = new StringDecoder('utf8');

console.log(decoder.write(Buffer.from([0xC2, 0xA2]))); // ¢
console.log(decoder.write(Buffer.from([0xE2, 0x82, 0xAC]))); // €

4. Handling Incomplete Multibyte Characters


If a character arrives in multiple chunks, StringDecoder buffers the incomplete bytes until the full character is available:


decoder.write(Buffer.from([0xE2]));
decoder.write(Buffer.from([0x82]));
console.log(decoder.end(Buffer.from([0xAC]))); // €

5. The StringDecoder Class


5.1 Constructor


  • new StringDecoder(encoding): Creates a new instance.
  • Default encoding: 'utf8'.

5.2 write(buffer)


  • Accepts Buffer, TypedArray, DataView, or string.
  • Returns a decoded string.
  • Stores incomplete multibyte sequences internally for the next call.

5.3 end([buffer])


  • Flushes any remaining buffered bytes.
  • Replaces incomplete characters with the appropriate substitution character.
  • Can optionally process one final chunk before ending.
  • The decoder can be reused after calling end().

6. Why Use StringDecoder?


  • Prevents corrupted output when decoding multibyte characters.
  • Ideal for streaming data where chunks may split characters.
  • Supports UTF‑8 and UTF‑16 safely.
  • Predictable behavior with incomplete sequences.

7. Common Use Cases


  • Decoding data from TCP sockets.
  • Processing chunked HTTP requests/responses.
  • Reading text files via streams.
  • Handling partial data in real‑time applications.

Conclusion


The StringDecoder module is an essential tool for safely decoding streamed or chunked text data in Node.js. By intelligently buffering incomplete multibyte sequences, it ensures clean, accurate string output and prevents the corruption that can occur with naive decoding methods.


Written & researched by Dr. Shahin Siami

Related Articles

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

Continue

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

Continue

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

Continue

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

Continue

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

Continue

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

Continue