node.js中的二进制结构

我正在写一个服务器,并通过TCP我收到缓冲区。 这个缓冲区是一个结构,

所以IC通常是这样做的:

typedef struct _ref_{ uint8_t x; uint8_t *y; uint8_t z[16]; }REF; 

与上面的代码无关,我的缓冲区可能如下所示:

 01 00 00 00 0A 

可以定义为:(小端)

 UINT16 UINT16 UINT8 

所以那将是

 1, 0, 10 

我想把它转换成一个json对象

 UINT16 is X, UINT16 is Y, UINT8 is Z 

那么结果会是

 x: 1, y: 0, z: 10 

但是怎么能在node.js中完成(不是浏览器相关的)


我看到restructjs,但它不支持null终止的string,string是长度特定的。

我也看到了struct-fu ,这个更新了一些,但仍然存在空string结束的问题。

像这样的东西?

 var buffer = your_input_data; var result = { x: buffer.readUInt16LE(0), y: buffer.readUInt16LE(2), z: buffer.readUInt8(4) } console.log(JSON.stringify(result)); 

find合适的库之后,我决定编写自己的支持空string的函数。

它被称为c-struct ,你可以在这里find它。

安装:

 npm install c-struct --save 

句法:

 var playerSchema = new _.Schema({ id: _.type.uint16, name: _.type.string(16), hp: _.type.uint24, exp: _.type.uint32, status: _.type.uint8, motd: _.type.string(), // null-terminated if no length motw: _.type.string(), // cstring if no length skills: [{ id: _.type.uint8, name: _.type.string(32), secret: _.type.uint40 }], position: { x: _.type.uint16, y: _.type.uint16 }, hash: _.type.uint48 });