Wednesday, 15 March 2017

Buffers filled with unicode zeroes

I'm trying to synchronously read parameters from console in node, I managed to do the following:

var load = function () {
    const BUFFER_LENGTH = 1024;
    const stdin = fs.openSync('/dev/stdin', 'rs');
    const buffer = Buffer.alloc(BUFFER_LENGTH);
    console.log('Provide parameter: ');
    fs.readSync(stdin, buffer, 0, BUFFER_LENGTH);
    fs.closeSync(stdin);
    return buffer.toString().replace(/\n*/, '');
}

It works, but here's a strange thing:

var loadedValue = load();
console.log(loadedValue); // displays "a", if I typed "a", so the result is correct
console.log({loadedValue}); // displays {a: 'a\n\u0000\u0000....'}

When I wrap the value in an object, the remaining BUFFER bits are showed in a string. Why is that? How can I get rid of them? Regexp on a string before making an object doesn't work.



via user99999

No comments:

Post a Comment