Node JS - 我无法同步使用 FS.Stat

Node JS - I Can't Use FS.Stat Synchronously

我有一个节点js函数。它正在检查所有文件夹中的某些文件,并将每个文件的最后写入日期与请求日期进行比较。如果有匹配的,我想存储该文件夹的路径。实际上,我的功能有效,但它正在异步进行日期控制。我尝试 fs.statSync 但它也没有用。当我使用 statSync 时,我无法获得任何控制台日志输出。

console.log('Collected Files - OutsideIF : ' + filesCollected);

它不会向我显示任何内容。连个空的都没有。而我的最后一个控制台日志 returns 是空的。

我在我的代码中添加注释。这是我的功能:

var scanFolders = function(){ 
  // Listing all directories and files in path
  fs.readdir(path,(err,files) => {
    // Creating Variable For Record Result
    var filesCollected = "";
    // Loop for every directory and file
    files.forEach(file=>{
      // If current path is a directory
      if (fs.lstatSync(path+'/'+file).isDirectory()){
        // Check that directory for certain files
        if((fs.existsSync(path+'/'+file+'/'+'LineChart.html')) && (fs.existsSync(path+'/'+file+'/'+'clip.mp4'))){
          // Check last write time for clip mp4
          fs.stat(path+'/'+file+'/clip.mp4', function (err, info){
            var day = info.mtime.getDate();
            var month = info.mtime.getMonth();
            var year = info.mtime.getFullYear();
            if (day < 10) {day = "0" + day;}
            if (month < 10) {month = "0" + month;}
            // Temp Date variable for compare them
            var tempDate = day + '-' + month + '-' + year;
            // I can see this console log it's working perfectly
            console.log('file date : ' + tempDate + ' FileName : ' + file);
            // Compare dates and if they are equal take that path to filesCollected Variable
            if (tempDate == '24-01-2018'){
              filesCollected += file + ';';
            // If i check this code block with console log it's working too.
            }
            // Last loop from this "Collected Files - OutsideIF" log is actually what 
            // i want. I put this for control code flow. But it's returning after 
            // "Collected Files :" console log below. So i can't return that data 
            console.log('Collected Files - OutsideIF : ' + filesCollected);
          });
          //end
        }
      }
    });
    //It's return empty because this code executing first. So i guess fs.stat is async
    console.log('Collected Files : ' + filesCollected);
  })
};

当您从 fs.stat to fs.statSync 转换时,您需要使用它的 return 值而不是传入回调。例如

fs.stat(path, function (err, info){
  ...
} );

大约等同于*:

try {
  const info = fs.statSync(path);
  ...
} catch ( err ) {

}

*除了异步和同步的区别, 并且使用 const 意味着 info 不能在 try 块中重新分配。