在我的Node js应用程序中,我有一个从文件中逐行读取的函数,将文件的内容存储在一个数组中,然后调用一个回调函数,并将数组传递给回调函数。
navigationItem
我面临的问题是Array
在读取文件并填充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);
}
数组之前正在运行回调。所以回调是用一个空数组运行的。阵列完全填满后如何让它运行?感谢。
答案 0 :(得分:1)
readline有一个close事件,该事件在“结束”
上触发所以,你的代码应该是
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);
});
}
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));
}
甚至
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));
}
但我不确定两个ES2015代码中哪一个更具可读性