Tag Archives: String Decoder

STRING DECODER MODULE IN NODE.JS

String Decoder Module in Node.js

STRING DECODER:

String decoder module in node.js is used to provide an API for decoding buffer object into strings. Also, this decoding is performed in a manner that UTF-8 and UTF-16 characters multibyte coding is preserved. The user might query string module in the following way:

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

STRING DECODER METHODS:

String decoder class has two methods which are as follows:

  • STRINGDECODER.WRITE(BUFFER):

This method is used to return the specified buffer as decoded string. The user passes buffer as the argument in this method. Let’s see an example as given below :

//name of the file : write.js
var stringDecoder = require(‘string_decoder’).StringDecoder;
var sd = new stringDecoder(‘utf8′);
var buff = Buffer(‘data to be buffered’);
//Print the buffered data
console.log(buff);
//Print the decoded buffer
console.log(sd.write(buff));

The user can also run it in the following way too:

>node write.js

<Buffer 64 61 74 61 20 74 6f 20 62 65 20 62 75 66 66 65 72 65 64>

data to be buffered

  • STRINGDECODER.END([BUFFER]): 

This method is used to return the remaining of the input stored in internal buffer.

  • buffer <Buffer> | <TypedArray> | <DataView> A Buffer, or TypedArray, or DataView containing the bytes to decode.
  • Returns: <string>

It returns any remaining input stored in the internal buffer as a string. Bytes representing incomplete UTF-8 and UTF-16 characters will be swapped with substitution characters appropriate for the character encoding.

If the buffer argument is provided, one final call to stringDecoder.write() is done before returning the remaining input.