gpt4 book ai didi

node.js - NodeJS : How to write a file parser using readStream?

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:23 25 4
gpt4 key购买 nike

我有一个二进制格式的文件:

格式如下:

[4 - header 字节] [8 个字节 - int64 - 读取以下字节数] [可变字节数(int64 的大小) - 读取实际信息]

然后重复,所以我必须首先读取前 12 个字节以确定还需要读取多少字节。

我已经尝试过:

var readStream = fs.createReadStream('/path/to/file.bin');
readStream.on('data', function(chunk) { ... })

我遇到的问题是, block 总是一次返回 65536 字节的 block ,而我需要更具体地说明我正在读取的字节数。

我一直在尝试readStream.on('readable', function() { readStream.read(4) })但它也不是很灵活,因为它似乎将异步代码变成同步代码,因为我必须将“读取”放在 while 循环中

或者 readStream 在这种情况下可能不合适,我应该使用它? fs.read(fd, 缓冲区, 偏移量, 长度, 位置, 回调)

最佳答案

以下是我建议作为 readStream 的抽象处理程序来处理您所描述的抽象数据的内容:

var pending = new Buffer(9999999);
var cursor = 0;
stream.on('data', function(d) {
d.copy(pending, cursor);
cursor += d.length;

var test = attemptToParse(pending.slice(0, cursor));
while (test !== false) {
// test is a valid blob of data
processTheThing(test);

var rawSize = test.raw.length; // How many bytes of data did the blob actually take up?
pending.copy(pending.copy, 0, rawSize, cursor); // Copy the data after the valid blob to the beginning of the pending buffer
cursor -= rawSize;
test = attemptToParse(pending.slice(0, cursor)); // Is there more than one valid blob of data in this chunk? Keep processing if so
}
});

对于您的用例,请确保 pending 缓冲区的初始化大小足以容纳您将要解析的最大可能的有效数据 blob(您提到了 int64;最大大小加上 header 大小)加上一个额外的 65536 字节,以防 blob 边界恰好发生在流 block 的边缘。

我的方法需要一个 attemptToParse() 方法,该方法获取缓冲区并尝试从中解析数据。如果缓冲区的长度太短(数据还没有到达足够的数量),它应该返回 false。如果它是一个有效的对象,它应该返回一些已解析的对象,该对象有办法显示它占用的原始字节(在我的示例中为 .raw 属性)。然后,您需要对 blob 进行任何处理 (processTheThing()),删除有效的数据 blob,将待处理的缓冲区移至剩余部分,然后继续。这样,您就不会拥有不断增长的pending缓冲区,或者一些“已完成”的 blob 数组。也许 processTheThing() 接收端的进程在内存中保存 blob 数组,也许将它们写入数据库,但在这个示例中,它被抽象掉了,所以这段代码只处理如何处理流数据。

关于node.js - NodeJS : How to write a file parser using readStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22051162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com