如何将文件的每一行转移到数组单元格?

我尝试用id读出一个文件并将其作为数组返回。 每行包含一个单一的ID。 我想将每个id传递给一个数组单元格。 这是我的代码:

var fs = require('fs'); var reader = fs.createReadStream('RTIdList.js', {encoding: 'utf8'}); reader.once( 'end' , function () { console.log( 'Read completed successfully.' ); }); var lineReader = require('readline').createInterface({ input: reader, }); function RTIdReader(){ var arrayPos = 0; var idArray = new Array(); lineReader.on('line', function (line) { console.log('Line from file:', line); idArray[arrayPos] = line; arrayPos++; }); console.log('idArray[0]: '+idArray[0]); return idArray; } RTIdReader(); 

你有一个想法,我做错了什么? 怎么会是对的?

@DrakaSAN:代码工作,直到填充数组。 我无法console.log或返回数组。 代码在lineReader.on之后停止

我从回合开始大约两周左右就很辛苦了。 而且猜测,我不明白他们。 这是我的尝试:

 var fs = require('fs'); function RT(idList){ console.log('RT works'); } function idList(){ var idArray = new Array(); var reader = fs.createReadStream('RTIdList.js', {encoding: 'utf8'}); reader.once( 'end' , function () { console.log( 'Read completed successfully.' ); }); var lineReader = require('readline').createInterface({ input: reader, }); return { lineReader.on('line', function (line) { console.log('Line from file:', line); idArray.push(line); return idArray; } } } RT(); 

为什么我的callback不起作用?

好吧,回到开始。 那是我开始的。

 var fs = require('fs'); var idArray = new Array(); var reader = fs.createReadStream('RTIdList.js', {encoding: 'utf8'}); reader.once( 'end' , function () { console.log( 'Read completed successfully.' ); }); var lineReader = require('readline').createInterface({ input: reader, }); lineReader.on('line', function (line) { console.log('Line from file:', line); idArray.push(line); }); 

在哪里以及如何回扣?

将数据添加到数组时,使用push可以将数据添加到数组中的某个对象,如同时尚一样。 差异很小,但以后可能会来咬你。

检查readline文档以了解如何使用它,您根本不需要读者。

您的回报在您的代码开始读取文件的同时发生,您需要检查asynchronous函数的工作方式。

工作代码提示:

根本不需要fs.createReadStream。

在数组中的所有id的callback将在.on('close', function () {/*here*/});

编辑:

在JavaScript中,你可以传递一个函数作为参数,并创build匿名函数。

因此,您不要在asynchronous代码中使用return ,而是将其余的代码作为parameter passing,按惯例称为callback

至于如何使用readline来读取文件,一个很好的例子就是在 5min内可以转换为你的用例的文档 。

编辑:

好的,我花了时间做代码。

(arg) => {}function (arg) {}

 const readline = require('readline'); const fs = require('fs'); function RT(file, callback) { let idArray = []; //Declare idArray const rl = readline.createInterface({ //Set and start readline input: fs.createReadStream(file) }); rl.on('line', (line) => { //For each line console.log('Line from file:', line); idArray.push(line); //Add it to the array }); rl.on('close', () => { //At the end of the file callback(idArray); //Call the rest of the code }); } RT('RTIdList.js', (idArray) => { console.log('Here is the idArray: ' + idArray); });