Thursday, April 23, 2020

Node.js string_decoder module

Node.js string_decoder module

nodejs string_decoder module

Node.js provides a string_decoder module for decoding Buffer objects into strings. This module provides an API to decode the buffers and preserve the encoding type(e.g. UTF-8, UTF-16) of character multi-byte representation. It works like buffer.toString() but provides additional support for UTF encoding.

The module can be included as,

var { StringDecoder } = require(‘string_decoder’);


The StringDecoder class provides only two methods


This method returns if any trailing input is left in the internal buffer as a decoded string.


The method returns a decoded string. This method skips incomplete bytes at the end of the buffer and leaves them ensuring that any incomplete multi-byte characters at the end of the Buffer, or Typed Array or DataView are stored in an internal buffer for the upcoming stringDecoder.write() or stringDecoder.end() call.

//include 'string_decoder' module
var {StringDecoder} = require('string_decoder');
var decoder = new StringDecoder('utf8');

buffer=Buffer.from("Hello Node.js","utf8");

console.log(decoder.write(buffer));//prints "hello Node.js"
console.log(buffer.toString());//prints "hello Node.js"

var cent = Buffer.from([0xC2, 0xA2]);

var euro = Buffer.from([0xE2, 0x82, 0xAC]);
<Buffer 48 65 6c 6c 6f 20 4e 6f 64 65 2e 6a 73>
Hello Node.js
Hello Node.js