简体   繁体   中英

Array is empty after readline data is pushed

I am trying to write a program, where I need to read data from a file line by line synchronously, store values line by line in an array using Array.push() . I am reading the file using the readline npm package. However, when I try to call the array after iterating through the whole file, it shows me an empty array.

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);

I think I am having a problem because of the asynchronous execution of this code. How can I fix this and print the content of the array in proper order as in the text file?

You need to listen to the close event and then print the array. close will be called once all lines have been read.

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

Also,

var Text = new Array;

Should be:

var Text = new Array();

or

var Text = [];

You have to wait for the lines to be read before logging the variable(in your case its Text ) value. You must wait for all the lines to be read by listening on close event, or do something in line event itself.

Your code should look something like below

    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);

Also you are not using the parameter InputStream that you are passing to AddText function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM