在Node.js中解析巨大的二进制文件

Parsing huge binary files in Node.js

本文关键字:巨大 二进制文件 Node js      更新时间:2023-09-26

我想创建Node.js模块,它应该能够解析巨大的二进制文件(有些大于200GB)。每个文件被划分为块,并且每个块可以大于10GB。我尝试使用流动和非流动方法读取文件,但问题是,在解析区块时已到达读取缓冲区的末尾,因此必须在下一个onData事件发生之前终止对该区块的解析。这就是我尝试过的:

var s = getStream();
s.on('data', function(a){
    parseChunk(a);
});
function parseChunk(a){
    /*
        There are a lot of codes and functions.
        One chunk is larger than buffer passed to this function,
        so when the end of this buffer is reached, parseChunk
        function must be terminated before parsing process is finished.
        Also, when the next buffer is passed, it is not the start of
        a new chunk because the previous chunk is not parsed to the end.
    */
}

将整个区块加载到进程内存中是不可能的,因为我只有8GB的RAM。如何从流中同步读取数据,或者如何在缓冲区结束时暂停parseChunk功能并等待新数据可用?

也许我遗漏了一些东西,但据我所知,我看不出为什么不能使用不同语法的流来实现这一点。我会用

let chunk;
let Nbytes; // # of bytes to read into a chunk
stream.on('readable', ()=>{
  while(chunk = stream.read(Nbytes)!==null) { 
    // call whatever you like on the chunk of data of size Nbytes   
  }
})

请注意,如果您自己指定块的大小,就像这里所做的那样,如果请求的字节数在流的末尾不可用,则会返回null。这并不意味着没有数据可以流式传输。因此,请注意,您应该期望返回一个大小<文件末尾的Nbytes