如何使用 node.js 为文本文件的每一行创建一个数组条目 [英] How to create an array entry for each line of a text file using node.js
问题描述
我无法从 node.js 中文本文件的每一行创建一个数组条目
I am having difficulty creating an array entry out of each line of a text file in node.js
我的数组叫做temp".我可以在以下代码中对每一行进行 console.log:
My array is called "temp." I am able to console.log each line in the following code:
var temp = [];
const readline = require('readline');
const fs = require('fs');
let rl = readline.createInterface({
input: fs.createReadStream('./lib/Sphinx.txt')
});
let line_no = 0;
rl.on('line', function(line) {
line_no++;
console.log(line); //this successfully prints out every line
temp.push(line); //this would ideally create a new array entry for each line
});
但是,当我运行此代码时:
However, when I run this code:
console.log(temp.length)
//returns 0
console.log(temp.size)
//returns undefined
异步函数调用导致这种情况发生.结果,我无法访问函数本身之外的数组值,这是唯一的目标.
Asynchronous function calls are causing this to happen. As a result, I am unable to access the array values outside of the function itself, which is the only objective.
感谢帮助.谢谢,纳库尔
Help is appreciated. Thanks, Nakul
推荐答案
rl.on('line', function (line) {
line_no++;
console.log(line); //this successfully prints out every line
temp.push(line); //this would ideally create a new array entry for each line
}).on('close', function (line) {
// EOF
console.log(temp);
console.log(temp.length);
});;
编写
console.log(temp.length)
而不是console.log(temp.size)
应该可以工作Write
console.log(temp.length)
instead ofconsole.log(temp.size)
that should work您应该在逐行读取时获得完整的数组,即在
close
事件上.You should get complete array at the end of your line by line read, i.e. on
close
event.这篇关于如何使用 node.js 为文本文件的每一行创建一个数组条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!