hexacyanide hexacyanide - 1 year ago 931
Node.js Question

Node.js: Count the number of lines in a file

I have large text files, which range between

. How can I count the number of lines in a file using

I have these limitations:

  • The entire file does not need to be written to memory

  • A child process is not required to perform the task

Answer Source

solution without using wc:

var i;
var count = 0;
  .on('data', function(chunk) {
    for (i=0; i < chunk.length; ++i)
      if (chunk[i] == 10) count++;
  .on('end', function() {

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 

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download