node.jspromisefilereaderes6-promiseline-by-line

nodejs read file line by line and get its content at the end


I want to use nodejs to read a file line by line and then when it finishes get the returned result as a json string. I was trying to do like this, but at the end the console.log prints undefined and not the list. I got the list and the end of the promise but how do I return it to the calling function in main.js?

I have my main.js file:

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

console.log(fct.myfunction());

and the romlist-parser.js has the following content:

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

Solution

  • Try this:

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

    P.S. This code can be improved further but for sake of simplicity and your understanding answer is limited to the style/code posted in the post. Else it can vary style to style.