Home > Web Front-end > JS Tutorial > body text

node.js implements code for reading file content line by line_node.js

WBOY
Release: 2016-05-16 16:42:53
Original
1357 people have browsed it

Before that, let’s introduce an NPM that reads file content line by line: https://github.com/nickewing/line-reader. Friends who need it can take a look.

Go directly to the 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);
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template