我有一个包含以下文件名的目录:
01.02.2010.txt
02.02.2010.txt
03.02.2010.txt
04.02.2010.txt
我已经阅读了没有扩展名的文件名:
fs.readdir('./files', function (err, items) {
items.forEach(function (file) {
console.log(file.slice(0,-5))
});
});
我想要的是从目录中删除最后两个日期最低的文件。
你知道怎么做吗node.js
,谢谢
我files
根据已经包含日期的文件的名称为列表变量中的每个文件生成日期。在dates
变量中有日期后,我对所有日期进行排序,因为文件列表的顺序可能错误。排序日期后,我只检索日期数组中的前两个元素,并根据日期生成文件名并将文件名存储在filesNames
变量中。
var files =["04.02.2010.txt","01.02.2010.txt","03.02.2010.txt", "02.02.2010.txt"];
// Loop through the list of file and generate date corresponding to the name of each file
var dates = []
files.forEach(function(date){
var matches = date.match(/^(.+)\.txt$/);
var dateTxt = matches[1].split('.');
var fileDate = new Date(dateTxt[2], dateTxt[1], dateTxt[0]);
dates.push(fileDate);
});
// Sort list of dates
dates.sort(function (date1, date2) {
return date1 - date2
});
// Get the 2 lowest dates
var datesToDeletes = dates.slice(0,2);
// Regenerates filesnames
var filesNames = []
datesToDeletes.forEach(function(d){
var date = d.getDate()
// Add 0 before date if the month has only one number
date = (String(date).length == 1)? "0" + date : date;
var month = d.getMonth()
// Add 0 before month if the month has only one number
month = (String(month).length == 1)? "0" + month : month;
var year = d.getFullYear();
var dateString = date + '.' + month + '.' + year;
var fileName = dateString + '.txt';
filesNames.push(fileName);
})
// Deletes files
filesNames.forEach(function(file){
var path = "" + file;
// I put console log just for debugging purpose
console.log(path)
// Delete each file
// Here you can delete the file because you have the name of the file in the path variable
/*
fs.unlink(path, (err) => {
throw err;
});
*/
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句