Return array from node.js readline module on close event

女生的网名这么多〃 提交于 2019-12-14 03:53:51

问题


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:


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


来源:https://stackoverflow.com/questions/52914673/return-array-from-node-js-readline-module-on-close-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!