0

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

All the examples in the other thread answer how to read a file line-by-line. But none of them focus on how to read a file line-by-line one-line-at-a-time.

To illustrate, I have adapted code from the accepted answer in the other thread:

let index = 0;

const rl = readline.createInterface({
    input: fs.createReadStream(path.resolve(__dirname, './countries.txt'))
});

rl.on('line', () => {
    console.log('line', ++index);

    rl.pause();
});

Depending on the speed of the machine executing the code, the output of running this program will be something along the lines of:

line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
...
line 564
line 565
line 566
line 567

How to read a file line-by-line one-line-at-a-time?

To emphasize the intention of using rl.pause in the example: I need to get 1 line from a file and halt further reading of the file until I explicitly request the second line.

Community
  • 1
  • 1
Gajus
  • 69,002
  • 70
  • 275
  • 438
  • Not an answer, but I found that https://github.com/nickewing/line-reader#usage abstracts the interface to read a file line by line. – Gajus May 06 '16 at 19:09

2 Answers2

2

I dont really understand why you use readline interface to read a file.

I suggest you to use split, such as

  var splitstream = fs.createReadStream(file).pipe(split())
  splitstream
    .on('data', function (line) {
      //each chunk now is a seperate line!
      splitstream.pause();
      setTimeout(function (){ splitstream.resume() }, 500);
    })

you will definitely get one line at a time.

** edited for the comment.

  • I need to get a line from a file and stop further processing until I explicitly ask for a new line. – Gajus May 06 '16 at 19:06
  • You pause and resume the stream if you need to. –  May 06 '16 at 19:14
  • 1
    readline is indeed to read a stream line-by-line according to the doc.... But it s mostly build to deal with stdin, when the user types in something and press [enter]. see https://nodejs.org/api/readline.html#readline_readline –  May 06 '16 at 19:24
0

Here is how you can read file line by line and process a line before reading the next line.

var fs=require('fs');
var readable = fs.createReadStream("data.txt", {
  encoding: 'utf8',
  fd: null
});
var lines=[];//this is array not a string!!!
readable.on('readable', function() {
  var chunk,tmp='';
  while (null !== (chunk = readable.read(1))) {
    if(chunk==='\n'){
      tmp='';
      lines.push(tmp);
    //  here tmp is containing a line you can process it right here.
    //  As i am just pushing the line in the array lines.
    //  use async if you are processing it asynchronously.
    }else
      tmp+=chunk;
  }
});
readable.on('end',function(){
  var i=0,len=lines.length;
  while(i<len)
    console.log(lines[i++]);
});
vkstack
  • 1,582
  • 11
  • 24