Node. js implements the code that reads the contents of the file line by line

  • 2020-03-30 03:28:51
  • OfStack

Here to introduce a line by line before you read the file content NPM:https://github.com/nickewing/line-reader, need friends can look at.

Direct code:


function readLines(input, func) {
  var remaining = '';
  input.on('data', function(data) {
    remaining += data;
    var index = remaining.indexOf('n');
    while (index > -1) {
      var line = remaining.substring(0, index);
      remaining = remaining.substring(index + 1);
      func(line);
      index = remaining.indexOf('n');
    }

  });

  input.on('end', function() {
    if (remaining.length > 0) {
      func(remaining);
    }
  });
}

function func(data) {
  container.push(data);
}

var input = fs.createReadStream(__dirname + '/ip_arr.txt');
readLines(input, func);


Related articles: