Node.js StringDecoder

The Node.js StringDecoder is utilized to decode buffer into string. It is like buffer.toString() yet gives additional help to UTF.

You need to utilize require('string_decoder') to utilize StringDecoder module.

  1. const StringDecoder = require('string_decoder').StringDecoder;  

Node.js StringDecoder Methods

StringDecoder class has two techniques only.

Method Description
decoder.write(buffer) It is utilized to restore the decoded string.
decoder.end() It is utilized to return trailing bytes, if any left in the buffer.

Node.js StringDecoder Example

Let's see a straightforward case of Node.js StringDecoder.

File: stringdecoder_example1.js

  1. const StringDecoder = require('string_decoder').StringDecoder;  
  2. const decoder = new StringDecoder('utf8');  
  4. const buf1 = new Buffer('this is a test');  
  5. console.log(decoder.write(buf1));//prints: this is a test  
  7. const buf2 = new Buffer('7468697320697320612074c3a97374''hex');  
  8. console.log(decoder.write(buf2));//prints: this is a test  
  10. const buf3 = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);  
  11. console.log(decoder.write(buf3));//prints: buffer  

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.