首页 > 解决方案 > 如何从目录中删除两个最低的文件(按其名称)

问题描述

我有一个具有以下文件名的目录:

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,谢谢

标签: javascriptarraysnode.jssorting

解决方案


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;
		});
	*/
})


推荐阅读