For-loop and async callback in node.js?

后端 未结 3 1337
猫巷女王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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 03:37

    You are right about needing to use a closure. You should wrap the contents of the for loop in a self-invoking function to preserve the value of i for each iteration.

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

提交回复
热议问题