Node.js String Decoder Module

String Decoder module is used to decode a stream of binary data into String.

Steps to use String Decoder Module:

1.) For using String Decoder Module, first we need to include this module in the code.This can be done as below:

var strDecoder = require(‘string_decoder’).StringDecoder;

2.) Get an object of String Decoder with utf-8 as character encoding.

var chEncdObj = new strDecoder(‘utf-8’);

2.) Use write method on string decoder object to convert buffer into string.

e.g. lets take an example to convert a string into buffer and then reconvert into string.

var buffer = Buffer(“This is String decoder module demo program”);

var decodedString = strDecoder.write(buffer);

Complete code is as below:

var strDecoder = require('string_decoder').StringDecoder;
var chEncdObj = new strDecoder('utf-8');
var buffer = Buffer("This is String decoder module demo program");


var decodedString = chEncdObj.write(buffer);

console.log("Decoded String = "+decodedString);

Save this as stringDecoderDemo.js and run this code as “node stringDecoderDemo.js” through command prompt.

Output of the above code is as below:

Decoded String = This is String decoder module demo program

Leave a Reply