如何使用nodejs运行脚本一定时间?

时间:2017-03-13 16:22:49

标签: javascript node.js cron

每当readDirectory调用时,我正在检查是否有任何文件创建日期是过去30天我想从direcotry中删除该文件。这是按预期工作并删除文件,但我不认为它的效率。因此,我希望每晚将comapreDates方法移至单独的文件并调用目录logs/St,并检查是否有任何文件过期30天后将其删除。它可行吗?

service.js

function readDirectory(callback) {
    var dirPath = './logs/St';
    var files = fs.readdirSync(dirPath);
    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;
                compareDates(fileInfo, filePath);
                objToReturn.push(fileInfo);
                callback();
            }
        });
    }, function(err) {
        //final callback when all files completed here send objToReturn to client
        callback(objToReturn);
    });
}
}

function compareDates(file, path) {
    var timeDiff = Math.abs(currentDate.getTime() - file.fileDate.getTime());
    var dayDifference = Math.ceil(timeDiff / (1000 * 3600 * 24));
    console.log('Days', dayDifference);
    console.log('FileName', file.filename);
    if (dayDifference >= 30) {
        fs.unlink(path, function(err) {
            if (err) {
                // file doens't exist
                console.info("File doesn't exist, won't remove it.");
            } else {
                console.log('removed file', file);
            }
        });

    }

}