首页 > 解决方案 > How to read a file containing c-struct in nodeJS?

问题描述

In NodeJS, I have to parse a binary file written in C, composed of binary c-struct.

This is the c-code I have to convert in NodeJS.


  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);

How to code the same in NodeJS?

标签: cnode.jsstruct

解决方案


I solved in this way, using c-struct module:

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);

推荐阅读