nodejs 逐行读取文件并在最后获取其内容

use*_*255 5 filereader node.js promise line-by-line es6-promise

我想使用 nodejs 逐行读取文件,然后在完成时将返回的结果作为 json 字符串获取。我试图这样做,但最后 console.log 打印 undefined 而不是列表。我得到了 Promise 的列表和结尾,但是如何将它返回给 main.js 中的调用函数?

我有我的 main.js 文件:

var fct = require('./romlist-parser');

console.log(fct.myfunction());
Run Code Online (Sandbox Code Playgroud)

并且 romlist-parser.js 具有以下内容:

var fs = require('fs');
var readline = require('readline');

exports.myfunction = function() {

    var promise = new Promise(function(resolve,reject) {
        var rd = readline.createInterface({
            input: fs.createReadStream('Atari 2600.txt'),
            console: false
        });

        var games = [];

        rd.on('line', function(line) {
            var arr = line.split(";");
            games.push({name:arr[0], title:arr[1]});
        });

        rd.on('close', function() {
            var json = JSON.stringify(games);
            resolve(games);
        });

    });

    promise.then((resolveResult) => {
        console.log(resolveResult);
        return resolveResult;
    });
};
Run Code Online (Sandbox Code Playgroud)

Zee*_*mon 2

尝试这个:

exports.myfunction = function() {

    var promise = new Promise(function(resolve,reject) {

        var games = [];
        var rl = readline('./Atari 2600.txt'); // provide correct file path

        rl.on('line', function (line, lineCount, byteCount) {
            // console.log(lineCount, line, byteCount);
            var arr = line.split(";");
            games.push({name:arr[0], title:arr[1]});
        })
        .on('close', function() {
            var json = JSON.stringify(games);
            resolve(games); // resolve(json); may be?? 
        })
        .on('error', function (e) {
            console.log("error", e);
            // something went wrong
        });
    });

    promise.then((resolveResult) => {
        console.log(resolveResult);
        return resolveResult;
    });
};
Run Code Online (Sandbox Code Playgroud)

PS 此代码可以进一步改进,但为了简单起见,您的理解答案仅限于帖子中发布的样式/代码。否则它可能会因风格而异。