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.