简体   繁体   English

如何使用Node.js在特定时间运行脚本?

[英]How to run a script certain time using nodejs?

whenever readDirectory invoked i am checking if any file created Date is past 30 days i want to remove that file from direcotry. 每当调用readDirectory时,我都会检查是否有任何文件创建日期超过30天,我想从目录中删除该文件。 This is working as expected and removing the files but i dont think its efficient. 这正在按预期方式工作并删除文件,但我认为其效率不高。 So I want to move comapreDates method to separate file and call directory logs/St every night and check if any file expired passed 30 days period remove it. 因此,我想将comapreDates方法移动到单独的文件中,并每晚每晚调用目录logs/St并检查是否有任何过期的文件经过30天的周期comapreDates其删除。 is it doable ? 这可行吗?

service.js 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);
            }
        });

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM