Thursday, 18 May 2017

How to run function when series of readFile calls finish in node.js?

In node.js, I have a module that loops through a folder of files. That actually has a function callback that triggers when it finishes reading from directory. However for each file it finds, I run a readFile command which is async function, to read the file, and that has a callback function too. The question is, how can I set it up so that there is a callback once the directory looping function finishes and also each of the readFile functions?

var klaw = require('klaw');
var fse = require('fs-extra');

var items = [];

klaw("items").on('data', function (item) {
    var dir = item.path.indexOf(".") == -1;
    // if its a file
    if (!dir) {
        var filename = item.path;
        if (filename.toLowerCase().endsWith(".json")) {
            fse.readFile(filename, function(err, data) {
                if (err) return console.error(err);
                items.push(JSON.parse(data.toString()));
            });
        }
    }
}).on('end', function () {

});



via omega

No comments:

Post a Comment