0

How do I write an array of integers as a bytestream to the client in Nodejs?

Suppose I've the array [17, 256, 82].

I use the content-type application/octet-stream.

Now, I want to return a response containing the binary stream 0x00 0x11 0x01 0x00 0x00 0x52, i.e., each integer is represented using two bytes in the stream.

How can I do this in Nodejs? I've been looking at fs, but can't find a way.

Attempt:

function intTo16BigEndianString(n) {
    var result = String.fromCharCode((n >> 8) & 0xFF);
    result += String.fromCharCode((n >> 0) & 0xFF);

    return result;
}

...

numbers = [23,256,19];

numbers = numbers.map(function(n) {
    return intTo16BigEndianString(n);
})
resp.write(numbers.reduce(function (acc, curr) {
    return acc + curr;
}));

However, the result is not plain binary output. Weird bytes get intermixed. I guess this is because, resp is not meant to deal with binary?

Shuzheng
  • 11,288
  • 20
  • 88
  • 186

1 Answers1

1

You need to add 'binary' enconding. By default the encoding is 'utf8', which may add additional bytes, when encoding your "binary" string.

numbers = numbers.map(function(n) {
    return utils.intTo16BigEndianString(n);
});

resp.write(numbers.reduce(function (acc, curr) {
    return acc + curr;
}), 'binary');
Nicolas Lykke Iversen
  • 3,660
  • 1
  • 11
  • 9