properly decode string from stream nodejs utf8

31/12/2019

wrong

const spawn = require('child_process').spawn;

var p = spawn('ls');

var stdout = '';
p.stdout.on('data', (data) => {
    // if data is incomplete, and you call toString('utf8'), stdout will have a mangled character appended
    // doesn't happen often but had to debug
    stdout += data.toString('utf8');
});
p.on('close', (code) => {
    console.log(stdout);
});

correct

const spawn = require('child_process').spawn;
const { StringDecoder } = require('string_decoder');

var p = spawn('ls');

var decoder = new StringDecoder('utf8');
var stdout = '';
p.stdout.on('data', (data) => {
    // this time data is appended to the decoder.
    // if the last character of data is incomplete, the decoder wil keep it, and return it on next call.
    // therefore stdout is always valid
    stdout += decoder.write(data);
});
p.on('close', (code) => {
    console.log(stdout);
});

Raccourcis