如何在nodeJS中读取包含c-struct的文件?

时间:2019-06-11 15:03:14

标签: c node.js struct

在NodeJS中,我必须解析一个用C编写的二进制文件,该文件由二进制c-struct组成。

这是我必须在NodeJS中转换的C代码。


  typedef struct INPUTPARM {                                     
    ushort inputFlag;                                    
    char inputName[20];
  }

  // ...
  FILE *fInp = NULL; 
  struct INPUTPARM inputParm;

  fInp = fopen(filePath, "rb");

  // in a loop, it reads one record every time

  fread ((void *)&inputParm, 1, sizeof(struct INPUTPARM), fInp);

如何在NodeJS中编写相同的代码?

1 个答案:

答案 0 :(得分:1)

我使用c-struct模块以这种方式解决了问题:

var fileData = Buffer.from(binaryFileData, 'binary');
var _ = require('c-struct');
var inputParam = new _.Schema({
  inputFlag: _.type.uint16,  // ushort
  inputName: _.type.string() // string is 0-terminated
});
// register to cache
_.register('InputParam', inputParam);

var out = [];
for (var i = 0; i < fileData.length; i+=22) {
  var partial = fileData.slice(i, i+22);
  out.push(_.unpackSync('InputParam', partial));
}
console.log(out);