我想删除某个目录中所有文件名以相同字符串开头的文件,例如我有以下目录:
public/
profile-photo-SDS@we3.png
profile-photo-KLs@dh5.png
profile-photo-LSd@sd0.png
cover-photo-KAS@hu9.png
所以我想应用一个函数来删除所有以字符串 profile-photo
开头的文件,最后在以下目录中:
public/
cover-photo-KAS@hu9.png
我正在寻找这样的功能:
fs.unlink(path, prefix , (err) => {
});
最佳答案
谢尔盖亚罗茨基 mentioned ,使用像 glob
这样的包可能是理想的,因为该包已经过测试并且可以使过滤文件变得更加容易。
话虽如此,您可以采用的一般算法方法是:
const fs = require('fs');
const { resolve } = require('path');
const deleteDirFilesUsingPattern = (pattern, dirPath = __dirname) => {
// default directory is the current directory
// get all file names in directory
fs.readdir(resolve(dirPath), (err, fileNames) => {
if (err) throw err;
// iterate through the found file names
for (const name of fileNames) {
// if file name matches the pattern
if (pattern.test(name)) {
// try to remove the file and log the result
fs.unlink(resolve(name), (err) => {
if (err) throw err;
console.log(`Deleted ${name}`);
});
}
}
});
}
deleteDirFilesUsingPattern(/^profile-photo+/);
关于javascript - 删除node js中某个目录下名称以某个字符串开头的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44076455/