【问题标题】:Parsing huge binary files in Node.js在 Node.js 中解析巨大的二进制文件
【发布时间】:2016-07-31 07:05:43
【问题描述】:

我想创建 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 函数并等待新数据可用?

【问题讨论】:

  • 当你使用流时,你将读/写和缓冲交给流。但是,您似乎想要精确控制读取的内容和读取时间。您为什么不直接从磁盘读取您想要读取的确切字节数,而不使用您无法完全控制的流?
  • @jfriend00。因为这些文件不必在我的硬盘上。 Stream 可以从服务器文件中获取,也可以从其他进程的一部分内存中获取,也可以从某个缓冲区获取。

标签: javascript node.js stream synchronization buffer


【解决方案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   
  }
})

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

【讨论】:

    猜你喜欢
    • 2013-04-07
    • 2011-07-11
    • 2010-10-29
    • 2023-03-15
    • 1970-01-01
    • 2021-12-21
    • 2021-05-19
    相关资源
    最近更新 更多