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?