我想从所有目录中获取文件信息后,便有了代码的进一步实现,但是我被困在这里,并且遇到了粘贴有问题的错误,任何想法在下面的代码中发生了什么错误?

cron.js

var fs = require('fs');
var path = require('path');
var async = require('async');
var directories = ['./logs/dit', './logs/st','./logs/uat']
function cronJob() {
directories.forEach(function(dir){
    var files = fs.readdir(dir);
    async.eachSeries(files, function(file,callback) {
            var filePath = path.join(dirPath, file);
            var fileInfo = {};
            fs.stat(filePath, function(err, stats) {
               if (err) {
                 console.info("File doesn't");
                } else {
                 fileInfo.fileDate = stats.birthtime;
                 fileInfo.filename = file;
                 console.log(fileInfo);
//                 compareDates(fileInfo,filePath);
//                 callback();
               }
            });
        });
})

}

cronJob();


错误

s\Ulog-0\ulog\app\serverfiles\logs\dit'
  at Error (native)
  at Object.fs.readdirSync (fs.js:808:18)
  at C:\Users\WebstormProjects\Ulog-0\ulog\app\serverfiles\cronJob
20
  at Array.forEach (native)
  at cronJob (C:\Users\WebstormProjects\Ulog-0\ulog\app\serverfile
obs.js:7:13)
  at Object.<anonymous> (C:\Users\\WebstormProjects\Ulog-0\ulog\app

最佳答案

readdir是异步的,因此您需要等待其回调以执行进一步的操作。

很难知道到底是什么问题,所以我包括了日志语句。

编辑

var fs = require('fs');
var path = require('path');
var async = require('async');
var directories = ['/../../logs/dit', '/../../logs/st', '/../../logs/uat'];

// loop through each directory
async.eachSeries(directories, function (dir, cb1) {
    var dir = __dirname + dir;
    console.log('reading', dir);
    // get files for the directory
    fs.readdir(dir, function (err, files) {
        if (err) return cb1(err);

        // loop through each file
        async.eachSeries(files, function (file, cb2) {
            var filePath = path.resolve(dir + '/' + file);
            // get info for the file
            fs.stat(filePath, function (err, stats) {
                if (err) return cb2(err);
                var fileInfo = { fileDate: stats.birthtime, filename: file };
                console.log('fileInfo', fileInfo);
                compareDates(fileInfo, filePath);
                cb2(null, fileInfo);
            });
        }, cb1);

    });
}, function (err, fileInfos) {
    if (err) {
        console.info('error', err);
        return;
    }
    // when you're done reading all the files, do something...
});

08-07 08:19