日志类似:
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),然后使用他们的JS客户端将这些数据泵入Cube(https://github.com/square/cube)。
首先,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对象,并提取有用的字段)。
什么是最好的方法做到这一点,最大化吞吐量?有没有一些方法,不会阻止在每行读取,或发送到立方体?
第三 – 我猜使用字符串拆分,和JS等效的contains(IndexOf!= -1?)将会比正则表达式快得多?有没有人在解析大量的文本数据在Node.js有很多经验?
干杯,
胜利者
解决方法
下面的解决方案可以使用stream&管。对于测试,我使用了一个2.1 gb文件与17.000.000记录。 Ram使用不超过60 mb。
var fs = require('fs'),util = require('util'),stream = require('stream'),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(){ console.log('Error while reading file.'); }) .on('end',function(){ console.log('Read entire file.') }) );
请让我知道它怎么回事!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。