Return array from node.js readline module on close

2019-07-22 03:36发布

I'm calling a function on the server side that opens a csv file and searches for a string in each line. On the close event, the function should return an array that contains the first 5 string matches from the csv file (in the first column). However, it seems the array is unaccessible outside the function (possibly due to asynchronous behaviour):

index.js

function calling_function()
{
    var a_string = "foo";
    var array = database_search(a_string);
    console.log(array); 
}

function database_search(a_string)
{
    var result = ["", "", "", "", ""];

    var csv_file = readline.createInterface({
        input: fs.createReadStream(__dirname + '/Static/a_file.csv')
    });

    var cntr = 0;

    csv_file.on('line', function (line) {
        if(line.indexOf(a_string) > -1)
        {
            if(cntr < 5)
            {
                result[cntr] = line.split(",")[0];
            }
            else
            {
                csv_file.close();
            }
            cntr++;
        }
    });

    csv_file.on('close', function() {
        return result; // not returning result array
    });
}

What would be the correct way to access an array outside the readline on close event?

1条回答
家丑人穷心不美
2楼-- · 2019-07-22 03:53

In the "csv_file.on" event you are in the scope of a callback function. In order to get the array you can do the following:

function calling_function()
 {
      var a_string = "foo";
       var array = []
       database_search(a_string ,arr => {
       array = arr 
      console.log(array);
  });

}

   function database_search(a_string ,callback)
  {
var result = ["", "", "", "", ""];

var csv_file = readline.createInterface({
    input: fs.createReadStream(__dirname + '/Static/a_file.csv')
});

var cntr = 0;

csv_file.on('line', function (line) {
    if(line.indexOf(a_string) > -1)
    {
        if(cntr < 5)
        {
            result[cntr] = line.split(",")[0];
        }
        else
        {
            csv_file.close();
        }
        cntr++;
    }
});

// notice i added the 'result' in the callback function parameter
csv_file.on('close', function(result) {
    callback(result)
});
}
查看更多
登录 后发表回答