我需要对 Javascript/Node.js 中的大型(5-10 Gb)日志文件进行一些解析(我正在使用 Cube)。
日志如下所示:
10:00:43.343423 I'm a friendly log message. There are 5 cats, and 7 dogs. We are in state "SUCCESS".
我们需要读取每一行,做一些解析(例如去掉 5
、7
和 SUCCESS
),然后将这些数据注入(inject)Cube ( https://github.com/square/cube ) 使用他们的 JS 客户端。
首先,Node 中逐行读取文件的规范方式是什么?
这似乎是网上相当普遍的问题:
- http://www.quora.com/What-is-the-best-way-to-read-a-file-line-by-line-in-node-js
- Read a file one line at a time in node.js?
很多答案似乎都指向一堆第三方模块:
- https://github.com/nickewing/line-reader
- https://github.com/jahewson/node-byline
- https://github.com/pkrumins/node-lazy
- https://github.com/Gagle/Node-BufferedReader
但是,这似乎是一项相当基本的任务 - 当然,在 stdlib 中有一种简单的方法可以逐行读取文本文件?
其次,我需要处理每一行(例如,将时间戳转换为 Date 对象,并提取有用的字段)。
如何做到这一点,最大限度地提高吞吐量?是否有某种方式不会阻止读取每一行或将其发送到 Cube?
第三 - 我猜想使用字符串拆分,JS 等价于 contains (IndexOf != -1?) 会比正则表达式快很多?有没有人在 Node.js 中解析大量文本数据方面有丰富的经验?
干杯, 维克多
最佳答案
我搜索了一种使用流逐行解析超大文件 (gbs) 的解决方案。所有第三方库和示例都不适合我的需求,因为它们不是逐行处理文件(如 1 、 2 、 3 、 4 ..)或将整个文件读入内存
以下解决方案可以使用流和管道逐行解析非常大的文件。为了测试,我使用了一个包含 17.000.000 条记录的 2.1 gb 文件。内存使用量不超过 60 mb。
首先,安装event-stream包装:
npm install event-stream
然后:
var fs = require('fs')
, es = require('event-stream');
var lineNr = 0;
var s = fs.createReadStream('very-large-file.csv')
.pipe(es.split())
.pipe(es.mapSync(function(line){
// pause the readstream
s.pause();
lineNr += 1;
// process line here and call s.resume() when rdy
// function below was for logging memory usage
logMemoryUsage(lineNr);
// resume the readstream, possibly from a callback
s.resume();
})
.on('error', function(err){
console.log('Error while reading file.', err);
})
.on('end', function(){
console.log('Read entire file.')
})
);
请告诉我进展如何!
关于node.js - 在 Node.js 中解析巨大的日志文件 - 逐行读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16010915/