使用Node.js进行条件二进制解包
我的任务是创建一个node.js程序,该程序有三个主要组件:侦听传入数据(以压缩二进制形式提供),解包并解析该数据,然后将其发布到postgreSQL数据库。我遇到的问题是,当前提供的所有npm库节点都不能很好地处理解包的条件格式 数据以通用格式提供:使用Node.js进行条件二进制解包,node.js,binary,conditional,unpack,Node.js,Binary,Conditional,Unpack,我的任务是创建一个node.js程序,该程序有三个主要组件:侦听传入数据(以压缩二进制形式提供),解包并解析该数据,然后将其发布到postgreSQL数据库。我遇到的问题是,当前提供的所有npm库节点都不能很好地处理解包的条件格式 数据以通用格式提供: 头球。这个片段固定在每个传入数据包上20个字节,因此易于解析 第一信息部分。这有一个可变的长度 第二信息部分。这有一个可变的长度 第三信息部分。这有一个可变的长度 幸运的是,在每种情况下,我都会得到每个部分的长度作为前两个字节 我有一个指南告诉我
var binary = require('binary');
var bufferpack = require('bufferpack');
//The data is received as a buffer in the main program.
exports.execute = function (data) {
//The first piece of information is 8 bytes thus requiring
//using binary npm. It is also big endian unsigned.
//Bytes 0 - 7:
var info1 = binary.parse(data).word64bu('data1').vars;
//The next info packet is 1 unsigned byte.
var info2 = bufferpack.unpack('B', data, 8);
//The next info packet is 9 bytes long, but is not collected
//because it is not required.
//The last packet then is 2 bytes long, little endian unsigned
//Bytes 18 - 19:
var info3 = bufferpack.unpack('<H', data, 18);
//End of header.
//The above code runs fine and returns the expected values correctly.
//However, the next section of data comes in as conditional and presents
//plenty of problems:
//Luckily, I am given the length of the next piece of data.
var firstSectionLength = bufferpack.unpack('<H', data, 20);
//Next, three data packets will be sent, each containing 1-30
//Bytes of data. This is my current solution:
var firstSectionInfo = bufferpack.unpack((modemInfoLength).toString() + 's', data, 22);
//The next two information sections follow the same patter as the above.
console.log(firstSectionInfo);
};
正如您所注意到的,python程序通过不同的参数解析变量info length,然后在node.js程序中解析所需的参数
如果您在
firstSectionInfo
中看到的是:
['ab\u0000cd\u0000']
我假定您要拆分数组中的唯一值。所以你可以做:
['ab\u0000cd\u0000'][0].split('\u0000')
您将获得值'ab'
,'cd'
和'
(顺便说一句,您一直在编写
/u0000
,但这不能对应于Python的\x00
)不幸的是,它没有返回数组['a'、'b'、'/u0000'、'c'、'd'、'/u0000'],而是返回数组['ab/u0000cd/u0000'],所有这些都在索引数组[0]上。您在注释中的“it”指的是什么?您是在谈论firstSectionInfo
的内容吗?是的,调用console.log时,var firstSectionInfo将打印出我在上述注释中提到的内容
['ab\u0000cd\u0000'][0].split('\u0000')