node js how to turn a string buffer into string code example

Example 1: buffer to string

Single Buffer
If you have a single Buffer you can use its toString method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8 if you don't provide a parameter, but I've explicitly set the encoding in this example.

var req = http.request(reqOptions, function(res) {
    ...

    res.on('data', function(chunk) {
        var textChunk = chunk.toString('utf8');
        // process utf8 text chunk
    });
});
Streamed Buffers
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8-character may be contained in the first Buffer (chunk) and the second byte in the second Buffer then you should use a StringDecoder. :

var StringDecoder = require('string_decoder').StringDecoder;

var req = http.request(reqOptions, function(res) {
    ...
    var decoder = new StringDecoder('utf8');

    res.on('data', function(chunk) {
        var textChunk = decoder.write(chunk);
        // process utf8 text chunk
    });
});
This way bytes of incomplete characters are buffered by the StringDecoder until all required bytes were written to the decoder.

Example 2: buffer to string

Your code is working. The buffer you have is actually the string "[object Object]".

let b = Buffer.from('[object Object]', 'utf8')
console.log(JSON.stringify(b))
// {"type":"Buffer","data":[91,111,98,106,101,99,116,32,79,98,106,101,99,116,93]}

console.log(b.toString('utf8'))
// [Object object]
The problem you need to figure out is why is a buffer with that string being sent. It seems like the sender of the buffer needs to call stringify or otherwise serialize the object before sending it. Then you can turn it back to a string with toString() and use JSON.parse() on the string.

Tags:

Misc Example