在 node.js (readline) 中逐行读取数据,但完成后对象始终为空

Reading data line by line in node.js (readline) but object always empty when done

我完全是 Node.js 的菜鸟(但我已经做了 21 年的开发人员,fwiw)。我正在尝试编写一个小型应用程序,它将读取一个 csv 文件并将其解析为一个对象。这是代码:

var getFile = (filename) => {

var columns = [],
    x = 0,
    linereader = readline.createInterface({
        input: fs.createReadStream('./import/' + filename)
    });

linereader.on('line', function (line) {
    columns[x] = {};
    columns[x].data = line.split("|");
    x++;
}).on('close', () => {
    return columns;
});

};

它工作正常,直到 return 对象 columns,通过调试器完美地创建了对象。但是,一旦超出 linereader 部分,它就是空的。

几分钟前我尝试添加 .on("close") 部分,但没有任何区别,即使我将 columns 传递给它也是如此。

这是异步的吗?我怎样才能得到它 return 我的对象?谢谢!

Node JS 是异步的,这意味着你必须等到文件读取操作完成,然后使用 columns 变量,所以你不能在行执行后立即 return 列,甚至在 [=12] =],而不是将 callback 函数作为参数传递给您的函数,并在 columns 准备好

时将 运行 callback
var getFile = (filename, callback) => {
    var columns = [],
        x = 0,
        linereader = readline.createInterface({
            input: fs.createReadStream('./import/' + filename)
        });

    linereader.on('line', function (line) {
        columns[x] = {};
        columns[x].data = line.split("|");
        x++;
    }).on('close', () => {
        callback(columns);
    });
};

// usage
getFile("path/to/file", (columns) => {
    console.log(columns.length)
})