[英]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);
}
});
}
}
See one of those modules: 请参阅以下模块之一:
and more modules here: 和更多模块在这里:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.