Reputation: 73998
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.
Upvotes: 0
Views: 567
Reputation:
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.
Upvotes: 2
Reputation: 1664
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++]);
});
Upvotes: 0