删除某个目录下的所有文件,其名称以节点js中的某个string开头

我想要删除所有文件的文件名以特定目录中的相同string开始,例如我有以下目录:

public/ profile-photo-SDS@we3.png profile-photo-KLs@dh5.png profile-photo-LSd@sd0.png cover-photo-KAS@hu9.png 

所以我想应用一个函数来删除所有以stringprofile-photo开始的文件,最后在下面的目录中有:

 public/ cover-photo-KAS@hu9.png 

我正在寻找这样的function:

 fs.unlink(path, prefix , (err) => { }); 

使用glob npm包: https : //github.com/isaacs/node-glob

 var glob = require("glob") // options is optional glob("**/profile-photo-*.png", options, function (er, files) { for (const file of files) { // remove file } }) 

正如Sergey Yarotskiy 所说 ,使用像glob这样的软件包可能是理想的,因为该软件包已经过testing,可以使过滤文件变得更容易。

这就是说,你可以采取一般的algorithm方法是:

 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+/);