node.js the return value within a forEach

0

I have the following node.js program

const fs = require('fs');

function walk(dir, done, emitter) {
let results = {};
emitter = emitter || new (require('events').EventEmitter);

fs.readdir(dir, (err, list) => {

    let pending = list.length;

    if(err || !pending) {
        return done(err, results);
    }

    list.forEach(file => {

        let dfile = '${dir}/${file}';
        fs.stat(dfile, (err, stat) => {

            //  You might want to check for errors here as well.
            if(err) {
                throw err;
            }
            if(stat.isDirectory()) {
                emitter.emit('directory', dfile, stat);
                return walk(dfile, (err, res) => {
                    results[file] = res;
                    !--pending && done(null, results);
                }, emitter);//bien porque no hay aqui .on del emitter?
            } 

            emitter.emit('file', dfile, stat);
            results[file] = stat;
            !--pending && done(null, results);
        });
    });
});

return emitter;
}

walk(".", (err, res) => {
console.log(require('util').inspect(res, {depth: null}));
}).on("directory", (path, stat) => {
console.log('Directory: ${path} - ${stat.size}');
})
.on("file", (path, stat) => {
console.log('File: ${path} - ${stat.size}');
});

the question of this recursive tree path algorithm, why do I have to return eventemitter emitter at each depth level? For the first one it is obvious if I could not chain the 'on' but in the call when it's directory I just do return walk (cons their args) but I do not chained .on in the end, that is, I do not return.walk (dfile, (function done), emitter) .on ("directory"), etc etc as in the first call And it can be very deep in the tree structure

    
asked by FJsanto 03.09.2018 в 20:27
source

0 answers