简体   繁体   English

如何在Node.js中将整数数组作为字节流写入客户端?

[英]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? 如何在Node.js中将整数数组作为字节流写入客户端?

Suppose I've the array [17, 256, 82] . 假设我有数组[17, 256, 82]

I use the content-type application/octet-stream . 我使用内容类型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. 现在,我想返回一个包含二进制流0x00 0x11 0x01 0x00 0x00 0x52的响应,即每个整数在流中使用两个字节表示。

How can I do this in Nodejs? 如何在Node.js中做到这一点? I've been looking at fs , but can't find a way. 我一直在看fs ,但是找不到办法。

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? 我猜这是因为, resp不是要处理二进制文件吗?

You need to add 'binary' enconding. 您需要添加'binary'编码。 By default the encoding is 'utf8' , which may add additional bytes, when encoding your "binary" string. 默认情况下,编码为'utf8' ,当对“二进制”字符串进行编码时,可能会添加其他字节。

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

resp.write(numbers.reduce(function (acc, curr) {
    return acc + curr;
}), 'binary');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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