关闭事件时从node

关闭事件时从node

本文介绍了关闭事件时从node.js readline模块返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在服务器端调用一个函数,该函数打开一个csv文件并在每一行中搜索一个字符串.在close事件上,函数应返回一个数组,该数组包含来自csv文件(在第一列中)的前5个字符串匹配项.但是,似乎无法在函数外部访问数组(可能由于异步行为):

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

关闭事件时在readline之外访问数组的正确方法是什么?

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

推荐答案

在"csv_file.on"事件中,您属于回调函数的范围.为了获得数组,您可以执行以下操作:

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

这篇关于关闭事件时从node.js readline模块返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:53