Node.js:计算文件中的行数 [英] Node.js: Count the number of lines in a file
本文介绍了Node.js:计算文件中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有大型文本文件,范围在30MB
和10GB
之间.如何使用Node.js
计算文件中的行数?
I have large text files, which range between 30MB
and 10GB
. How can I count the number of lines in a file using Node.js
?
我有以下限制:
- 不需要将整个文件写入内存
- 不需要子进程来执行任务
推荐答案
不使用wc的解决方案:
solution without using wc:
var i;
var count = 0;
require('fs').createReadStream(process.argv[2])
.on('data', function(chunk) {
for (i=0; i < chunk.length; ++i)
if (chunk[i] == 10) count++;
})
.on('end', function() {
console.log(count);
});
速度较慢,但您可能没有想到的那么多-140M +文件(包含node.js加载&的0.6s)启动时间
it's slower, but not that much you might expect - 0.6s for 140M+ file including node.js loading & startup time
>time node countlines.js video.mp4
619643
real 0m0.614s
user 0m0.489s
sys 0m0.132s
>time wc -l video.mp4
619643 video.mp4
real 0m0.133s
user 0m0.108s
sys 0m0.024s
>wc -c video.mp4
144681406 video.mp4
这篇关于Node.js:计算文件中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文