1

在这里,我在执行回调函数on.close的函数中使用Readline模块。它以预期的顺序执行(代码on.close,然后是回调中的代码传递给它,这可以通过 console.log 语句看到),但是只有最终数组的一部分被复制(就像代码没有及时完成执行)。

示例输出:

First: First Thing, 1, Second Thing, 2, Third Thing 3
Second: First Thing, 1

我怎样才能得到这行代码:

console.log("Second: " + result);

像复制整个数组一样执行(不将其全部移动到一个函数中或使用异步/等待)?

////////// Required Packages and Initialization //////////
var express = require("express");
var fs = require("fs");
var readline = require("readline");
var app = express();

app.use(express.static(__dirname + '/some_folder'));

app.listen(3000);

////////// Request Handler //////////
app.get("/some_request", function(req, res) {
    req.setTimeout(20000);
    input_data = ["First thing", "Second thing", "Third thing"]; // Already in alphabetical order
    file_search(input_data, "a_file.csv", function(output_data) {
        res.json(output_data);
    });
});

////////// Functions //////////
function file_search(name_array, FileName, callback)
{
    csv_fetch_array(name_array, FileName, function(result) {
        console.log("Second: " + result);  // Executes second as expected, but does not contain whole result array, cut short <-----
        callback(result);
    });
}

function csv_fetch_array(name_array, FileName, callback)
{
    var cntr = 0;
    var result = [];
    var len = name_array.length;

    if (!(FileName))
    {
        callback(result);
    }

    var file_stream = fs.createReadStream(__dirname + '/some_folder/' + FileName);

    file_stream.on('error', function (err) {
        callback(result);
    });

    var csv_file = readline.createInterface({
        input: file_stream
    });

    // csv file arranged in alphabetical order
    csv_file.on('line', function (line) {
        var search = line.split(",");
        var name_search = search[0];

        ///// Logic to hop to next phrase if past current one alphabetically /////
        if (name_search == name_array[cntr])
        {
            result.push(search);
            if (++cntr >= len)
            {
                csv_file.close();
                csv_file.removeAllListeners(); // Otherwise readline continues to empty buffer
            }
        }
        else if (name_search > name_array[cntr])
        {
            if (++cntr >= len)
            {
                csv_file.close();
                csv_file.removeAllListeners();
            }
            else if(name_search == name_array[cntr])
            {
                result.push(search);
                if (++cntr >= len)
                {
                    csv_file.close();
                    csv_file.removeAllListeners();
                }
            }
        }
    });

    csv_file.on('close', function() {
        console.log("First: " + result); // Correct result here, executes first <-----
        callback(result);
    });
}
4

0 回答 0