简体   繁体   中英

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

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 , ie, 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?

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM