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

5 javascript buffer synchronization stream node.js

我想创建Node.js模块,它应该能够解析巨大的二进制文件(大于200GB).每个文件被分成块,每个块可以大于10GB.我尝试使用流动和非流动的方法来读取文件,但问题是因为在解析块时达到了readed缓冲区的结束,因此必须在下一个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.
    */
}
Run Code Online (Sandbox Code Playgroud)

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

Wil*_*ven 1

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

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   
  }
})
Run Code Online (Sandbox Code Playgroud)

请注意,如果您自己指定块的大小(如此处所做的那样),则null如果请求的字节数在流末尾不可用,则将返回该块的大小。这并不意味着不再有数据可传输。因此请注意,您应该期望Nbytes在文件末尾返回一个大小为 < 的“修剪”缓冲区对象。