删除某个目录中名称以节点js

时间:2017-05-19 18:10:57

标签: javascript node.js fs unlink

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

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

});

2 个答案:

答案 0 :(得分:3)

作为Sergey Yarotskiy 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+/);

答案 1 :(得分:2)

使用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
    }
})
相关问题