javascript - 如何从目录中删除两个最低的文件(按其名称)
问题描述
我有一个具有以下文件名的目录:
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;
});
*/
})
推荐阅读
- 3d - 基于共享顶点的多边形分组
- coq - 如何在 Coq 中推广方程两边的变量?
- image - 在没有右键菜单的情况下加载图像后保存图像
- java - Lucene 图像检索 closeWriter() 错误
- kivy - 如何使用 virtualenv 在 PyCharm 中创建 Python Kivy 项目?
- javascript - 如何修复可调整大小的可拖动元素的纵横比?
- node.js - 功能预部署错误:命令以非零退出代码2“导入问题”终止
- python - 矩形的其他两个点给出两个点和宽度
- reactjs - 如何删除 PrimeReact 的菜单栏中的菜单栏按钮?
- python-3.x - 当属性存在并返回回退时getattr()没有获取属性