Reputation: 129
In my Node js application I have a function that reads line by line from a file, stores the contents of the file in an array and then calls a callback function with the array passed to the callback.
function readFile(callback)
{
var fs = require('fs'), readline = require('readline');
var rd = readline.createInterface({
input: fs.createReadStream('./file.txt'),
output: process.stdout,
terminal: false
});
var data = [];
rd.on('line', function(line) {
data.push(line);
});
callback(data);
}
The problem I'm facing is that readFile
is running the callback before the file is read and the data
array is filled. So the callback is running with an empty array. How can I make it run once the array is fully filled? Thanks.
Upvotes: 0
Views: 1022
Reputation: 1
readline has a close event which is fired on "end"
So, your code should be
function readFile(callback) {
var fs = require('fs'), readline = require('readline');
var rd = readline.createInterface({
input: fs.createReadStream('./file.txt'),
output: process.stdout,
terminal: false
});
var data = [];
rd.on('line', function(line) {
data.push(line);
}).on('close', function () {
callback(data);
});
}
in ES2015:
function readFile(callback) {
var fs = require('fs'), readline = require('readline');
var rd = readline.createInterface({
input: fs.createReadStream('./file.txt'),
output: process.stdout,
terminal: false
});
var data = [];
rd.on('line', line => data.push(line)).on('close', () => callback(data));
}
or even
function readFile(callback) {
var fs = require('fs'),
readline = require('readline'),
data = [];
readline.createInterface({
input: fs.createReadStream('./file.txt'),
output: process.stdout,
terminal: false
})
.on('line', line => data.push(line))
.on('close', () => callback(data));
}
but I'm not sure which of the two ES2015 codes is more readable
Upvotes: 1