Read a file one line at a time in node.js?

前端 未结 29 1088
深忆病人
深忆病人 2020-11-22 04:33

I am trying to read a large file one line at a time. I found a question on Quora that dealt with the subject but I\'m missing some connections to make the whole thing fit to

29条回答
  •  情深已故
    2020-11-22 04:59

    there is a very nice module for reading a file line by line, it's called line-reader

    with it you simply just write:

    var lineReader = require('line-reader');
    
    lineReader.eachLine('file.txt', function(line, last) {
      console.log(line);
      // do whatever you want with line...
      if(last){
        // or check if it's the last one
      }
    });
    

    you can even iterate the file with a "java-style" interface, if you need more control:

    lineReader.open('file.txt', function(reader) {
      if (reader.hasNextLine()) {
        reader.nextLine(function(line) {
          console.log(line);
        });
      }
    });
    

提交回复
热议问题