loading each file of a folder as json array

user3601578

I have a folder of JSON files on the filesystem. Now I'm trying to load each JSON file into an object which works fine. Problem starts when I try to push each object into an array. My loadJSONFolderFiles() only returns an array of promises.

function loadJSONFolderFiles(p_path) {
    var deferred = Q.defer();
    var subfiles = [];
    fs.readdir(p_path, function (err, files) {
        if (err) {
            return rxError("internal", 2002, "could not read folder");
        }
        files.forEach(function (subfile) {
            var deferredLink = Q.defer();
            var folderFilePath = p_path + "/" + subfile;
            console.log("accessing " + folderFilePath);                

            // loadJSONFile() tested and works fine
            loadJSONFile(folderFilePath).then(function (p_file) {
                console.log("adding file " + folderFilePath);
                deferredLink.resolve(p_file);
            });
            subfiles.push(deferredLink.promise);
        });
        deferred.resolve(subfiles);
    });
    return deferred.promise;
}
deostroll

Because you are pushing promises into the subfiles array.

Here is a simple fix. It can have errors when you run it, but you should at least be in an easier position to fix them in case you run into problems:

function loadJSONFolderFiles(p_path) {
    var deferred = Q.defer();
    var subfiles = [];
    fs.readdir(p_path, function (err, files) {
        if (err) {
            return rxError("internal", 2002, "could not read folder");
        }
        var total = files.length;
        files.forEach(function (subfile) {
            //var deferredLink = Q.defer();
            var folderFilePath = p_path + "/" + subfile;
            console.log("accessing " + folderFilePath);                

            // loadJSONFile() tested and works fine
            loadJSONFile(folderFilePath).then(function (p_file) {
                console.log("adding file " + folderFilePath);
                //deferredLink.resolve(p_file);
                subfiles.push(p_file);
                if(subfiles.length === total) {
                    deferred.resolve(subfiles);
                }
            });

        });
        //deferred.resolve(subfiles);
    });
    return deferred.promise;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related