推送读​​取数据后,数组为空

时间:2017-03-23 16:33:26

标签: javascript arrays node.js asynchronous readline

我正在尝试编写一个程序,我需要同步逐行读取文件中的数据,使用Array.push()在数组中逐行存储值。我正在使用readline npm包读取文件。但是,当我在迭代整个文件后尝试调用数组时,它会显示一个空数组。

var fs = require('fs'),
    readline = require('readline'),
    stream = require('stream');

var instream = fs.createReadStream('sample.txt');
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;
function printArray(ArrayVar){
    console.log(ArrayVar);
    }
function AddText(InputStream){
    var Text = new Array;
    var rl = readline.createInterface({
        input: instream,
        output: outstream,
        terminal: false
    });
    rl.on('line',function(line){
        Text.push(line);
    });
    return Text;
    }

var a = AddText(instream);
printArray(a);

由于此代码的异步执行,我认为我遇到了问题。如何修复此问题并按照文本文件中的正确顺序打印数组内容?

2 个答案:

答案 0 :(得分:1)

您需要收听close事件,然后打印数组。一旦读完所有行,将调用close

rl.on('close', function() {
   console.log(Text)
});

另外,

var Text = new Array;

应该是:

var Text = new Array();

var Text = [];

答案 1 :(得分:1)

在记录变量(在您的情况下为Text)值之前,您必须等待读取行。 您必须通过聆听close事件等待读取所有行,或者在line事件本身中执行某些操作。

您的代码应如下所示

    var fs = require('fs'),
     readline = require('readline'),
     stream = require('stream');

    var instream = fs.createReadStream('sample.txt');
    var outstream = new stream;
    outstream.readable = true;
    outstream.writable = true;

    function printArray(ArrayVar){
        console.log(ArrayVar);
        }

    function AddText(InputStream){
        var Text = new Array;
        var rl = readline.createInterface({
            input: instream,
            output: outstream,
            terminal: false
        });

        rl.on('line',function(line){
            Text.push(line);
        });

        rl.on('close', function(){
            printArray(Text)
        })
        }

    var a = AddText(instream);

此外,您没有使用要传递给InputStream函数的参数AddText