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

詹卢卡B.

在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中编写相同的代码?

詹卢卡B.

我使用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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章