Waiting for the end of a recursive readdir function

I am using recursive readdir to read the entire directory tree to put it into the database.

My problem is that I am trying to stop the following lines of code until all readdir / insert into the database is finished.

I was looking for a solution in promises, but on the first call of my function (so in the first folder of the tree) the promise is fulfilled ...

Any idea?

function readsousdir(path, db, db2) {
    var Datastore = require('nedb');
    var fs = require('fs');
    fs.readdir(path + '\\', function (err, files) {
        files.forEach(function (file) {
            fs.stat(path + '\\' + file, function (err, stats) {
                var foldertrue = stats.isDirectory();
                var filetrue = stats.isFile() == true;
                if (foldertrue == true) {
                    var doc;
                    doc = folderdb(path + '\\' + file);
                    db2.insert(doc);
                    readsousdir(path + '\\' + file, db, db2);
                }
                if (filetrue) {
                    doc = pistedb(path + '\\' + file, []);
                    db.insert(doc);

                }
            });
        });
    });
}

      

+3


source to share


1 answer


Using BlueBird, you can use reduce

:

var fs = Promise.promisifyAll(require("fs"));

function readsousdir(path, db, db2) {
    var Datastore = require('nedb');
    return fs.readdirAsync(path + '\\').reduce(function(_, file){
        return fs.statAsync(path + '\\' + file)
        .then(function(stats){
            var foldertrue = stats.isDirectory();
            var filetrue = stats.isFile() == true;
            if (foldertrue == true) {
                var doc;
                doc = folderdb(path + '\\' + file);
                db2.insert(doc);
                return readsousdir(path + '\\' + file, db, db2)
            }
            if (filetrue) {
                doc = pistedb(path + '\\' + file, []);
                db.insert(doc);
            }
        });
    });
}

      



Suppose your db library returns promises and you want to wait for the insert, you would do

function readsousdir(path, db, db2) {
    var Datastore = require('nedb');
    return fs.readdirAsync(path + '\\').reduce(function(_, file){
        return fs.statAsync(path + '\\' + file)
        .then(function(stats){
            var foldertrue = stats.isDirectory();
            var filetrue = stats.isFile() == true;
            if (foldertrue == true) {
                var doc;
                doc = folderdb(path + '\\' + file);
                return db2.insert(doc).then(function(){
                    return readsousdir(path + '\\' + file, db, db2)
                });
            }
            if (filetrue) {
                doc = pistedb(path + '\\' + file, []);
                return db.insert(doc);
            }
        });
    });
}

      

+4


source







All Articles