I am trying to read a file line by line using nodejs readline
, for each line I want to perform some functions asynchronously, and then continue till the end of file.
const readline = require("readline");
const fs = require("fs");
let rl = readline.createInterface({
input: fs.createReadStream('b'),
crlfDelay: Infinity
});
rl.on('line', async (line) => {
console.log('start line');
await both();
console.log('end line');
});
rl.on('close', () => {
console.log('read complete');
});
function one() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('two'), 2000);
});
}
function two() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('two'), 3000);
});
}
async function both() {
ap = [];
ap.push(one());
ap.push(two());
console.log('processing line');
await Promise.all(ap);
console.log('line processed');
}
The file b
can be any file with some lines, say,
1
2
3
4
5
6
7
The output that I am expecting something like:
start line
line processing
line processed
end line
.
.
.
However, I am unable to maintain order.
To my understanding, it seems the 'line'
event is getting emitted which is calling the callback again and again!.
Is there any way we can make this event to wait until the event in hand is processed asynchronously(various steps running asynchronously) and after that repeat.
**Important Upadate ** So the file for the use case is going to contain around >5GB of CSV Text. And we have a memory constraint of <3GB and max time 15 minutes (AWS Lambda).