For-loop and async callback in node.js?

后端 未结 3 1334
猫巷女王i
猫巷女王i 2020-12-05 02:49

I\'m new to JavaScript and to node.js. I want to loop through a directory and add all file stat (not other directories) to an array. As you see below there is a problem with

3条回答
  •  半阙折子戏
    2020-12-05 03:35

    One way is to rewrite the innards of the loop to use a closure:

    fs.readdir(SYNCDIR, function(err1, files) {
        var filesOnly = [];
        if(!err1) {
            for(var i = 0; i < files.length; i++) {
                (function(index) {
                    var imgFilePath = SYNCDIR + '/' + files[index];
                    fs.stat(imgFilePath, function(stat){
                        if (stat.isFile()){
                            filesOnly[index] = stat;
                        }
                    });
                })(i);
            }
        }
    });
    

    A better looking example, achieving the same, using Array.prototype.forEach:

    fs.readdir(SYNCDIR, function(err1, files) {
        var filesOnly = [];
        if(!err1) {
            files.forEach(function(file, i) {
                var imgFilePath = SYNCDIR + '/' + file;
                fs.stat(imgFilePath, function(stat){
                    if (stat.isFile()){
                        filesOnly[i] = stat;
                    }
                });
            });
        }
    });
    

提交回复
热议问题