节点JS - 我不能同步使用FS.Stat

时间:2018-03-12 22:04:38

标签: node.js fs

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

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

它不会向我展示任何东西。甚至不是空的。我的上一个控制台日志返回空。

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

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);
  })
};

1 个答案:

答案 0 :(得分:2)

当您从fs.stat转换为fs.statSync时,您需要使用其返回值而不是传入回调。 EG。

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

大致相当于*:

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

}

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