【问题标题】:Return array from node.js readline module on close event在关闭事件时从 node.js readline 模块返回数组
【发布时间】:2019-03-25 15:54:00
【问题描述】:

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

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 之外的数组的正确方法是什么?

【问题讨论】:

    标签: node.js csv stream readline fs


    【解决方案1】:

    在“csv_file.on”事件中,您处于回调函数的范围内。 为了获取数组,您可以执行以下操作:

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

    【讨论】:

    • 它似乎仍然返回 undefined
    • 尝试记录结果 csv_file.on('close', function(result) { console.log(result) callback(result) });看看它是否按预期返回结果。
    • 好的,只需对您的答案稍作调整即可使用它:) 只需在 readline 关闭匿名回调函数中将“result”作为参数传递(因为它创建了一个新变量“结果”而不是使用包含数组的原始“结果”): csv_file.on('close', function() {callback(result) });
    猜你喜欢
    • 2020-06-13
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 2016-04-01
    • 2013-05-21
    • 1970-01-01
    • 2014-01-01
    相关资源
    最近更新 更多