我有一个简单的脚本,它使用 readLine api 处理一个大的主机名文件,它逐行读取,并且对于每个主机名,我调用一个异步 dns 函数来获取与主机名相关的 IP 地址。
这是我的代码:
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);
});
});
问题是发出关闭事件时 res 数组不包含所有结果,一旦执行了所有 dns 请求,我该如何运行回调?
谢谢