c - 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?
解决方案
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);
推荐阅读
- arrays - 将“喜欢”的图像保存到本地存储
- scala - Scala 中的类型不匹配与 IDEA 和 FP
- reactjs - 如何导航到不同的屏幕而不在本机反应中显示屏幕
- linux - 无法删除旧的 Docker 网络设置
- asp.net-core-mvc - ASP.NET Core MVC:使用远程输入验证
- javascript - javascript - 如何有条件地返回 Json
- c# - 替换一个字节的数据
- mysql - 如何杀死窗口中的所有MySQL进程
- c++ - co_return vs. co_yield 当右手边是临时的
- python - socket.gaierror: [Errno 11001] getaddrinfo failed for python and local mysql server