删除node js中某个目录下名称以某个字符串开头的所有文件

Delete all files in a certain directory that their names start with a certain string in node js

我想删除某个目录中所有文件名以相同字符串开头的文件,例如我有以下目录:

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) => {

});

使用 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 这样的包可能是理想的,因为该包已经过测试并且可以使过滤文件更加容易。

也就是说,您可以采用的一般算法方法是:

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