This answer Read a file one line at a time in node.js? shows how to read a file line by line.
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('file.in')
});
lineReader.on('line', function (line) {
console.log('Line from file:', line);
});
lineReader.on('close', function (line) {
console.log('Finished');
});
But if I make that callback an async
function so that I can do something like validate and transform each line and write it into a different file or to an API, then it doesn't work. The 'close' event gets fired without waiting for the individual lines to finish their async functions.
Is there a way to process a file line by line asynchronously using readline
or any libraries built in to Node.js?
What's the simplest way to get this to work?
I need to do it line by line because the files are very large and memory would be completely consumed otherwise.