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

前端 未结 29 1375
深忆病人
深忆病人 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 05:08

    I have a little module which does this well and is used by quite a few other projects npm readline Note thay in node v10 there is a native readline module so I republished my module as linebyline https://www.npmjs.com/package/linebyline

    if you dont want to use the module the function is very simple:

    var fs = require('fs'),
    EventEmitter = require('events').EventEmitter,
    util = require('util'),
    newlines = [
      13, // \r
      10  // \n
    ];
    var readLine = module.exports = function(file, opts) {
    if (!(this instanceof readLine)) return new readLine(file);
    
    EventEmitter.call(this);
    opts = opts || {};
    var self = this,
      line = [],
      lineCount = 0,
      emit = function(line, count) {
        self.emit('line', new Buffer(line).toString(), count);
      };
      this.input = fs.createReadStream(file);
      this.input.on('open', function(fd) {
        self.emit('open', fd);
      })
      .on('data', function(data) {
       for (var i = 0; i < data.length; i++) {
        if (0 <= newlines.indexOf(data[i])) { // Newline char was found.
          lineCount++;
          if (line.length) emit(line, lineCount);
          line = []; // Empty buffer.
         } else {
          line.push(data[i]); // Buffer new line data.
         }
       }
     }).on('error', function(err) {
       self.emit('error', err);
     }).on('end', function() {
      // Emit last line if anything left over since EOF won't trigger it.
      if (line.length){
         lineCount++;
         emit(line, lineCount);
      }
      self.emit('end');
     }).on('close', function() {
       self.emit('close');
     });
    };
    util.inherits(readLine, EventEmitter);
    

提交回复
热议问题