String Decoder module methods in node.js

The tutorial provides the details on the node.js string decoder module. The node.js string decoder module provides the API for decoding the buffer objects into the string with the support for multi-byte UTF-8 and UTF-16 characters. The String Decoder instance is validated that decoded string should not contain incomplete multi byte characters when the buffer instance is defined /written as the String Decoder instance, The node.js string decoder module can be accessed using the command

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

Node.js String Decode Methods

The below given are the available methods in the string decoder API

String Decoder MethodString Decoder Method Description
new StringDecoder([encoding])uses the encoding UTF-8 for the decoded string
encoding – <string>
stringDecoder.end([buffer])The buffer ( buffer or typedArray orDataView) decoded string checks for the incomplete UTF-8 and UTF-16 characters to be replaced with substitution characters for the character encoding
buffer – <buffer> – contains byte to decode
return -<string>
stringDecoder.write(buffer)The buffer ( buffer or typedArray orDataView) decoded string checks for the incomplete UTF-8 and UTF-16 characters to be omitted for the character encoding
buffer – <buffer> – contains byte to decode
return -<string>

Node.js String Decoder Example

const { StringDecoder } = require('string_decoder');
const decoder = new StringDecoder('utf8');
const cent = Buffer.from([0xC2, 0xA2]);
console.log(decoder.write(cent));
const euro = Buffer.from([0xE2, 0x82, 0xAC]);
console.log(decoder.write(euro));