I have a simple script that processes a large file of hostnames using readLine api, it reads line by line, and for every hostname I call an asynchronous dns function to get an ip address related to the hostname.
here is my code:
const readline = require('readline')
, fs = require('fs')
, dns = require('dns');
var res = [];
const rl = readline.createInterface({
input: fs.createReadStream('hostnames.csv')
});
rl.on('line', function (line) {
var parts = line.split(',');
dns.resolve4(parts[1], function (error, ips) {
if (error) return console.log('dns__error: ' + error);
res.push({ id:parts[0], hostname:parts[1], ips:ips });
});
});
rl.on('close', function () {
console.log(res.length);
fs.writeFile('hostnames.json', JSON.stringify(res), function (error) {
if (error) console.log('fs__writeFile__error: ' + error);
});
});
the problem is when the close event is emitted the res array does not contain all results, How can I run a callback once all dns requests are performed?
Thanks