【问题标题】:Delete all files in a certain directory that their names start with a certain string in node js删除节点js中某个目录中名称以某个字符串开头的所有文件
【发布时间】:2021-02-14 15:08:33
【问题描述】:

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

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

});

【问题讨论】:

    标签: javascript node.js fs unlink


    【解决方案1】:

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

    【讨论】:

    • 这对我很有帮助,我确实必须将取消链接中的 resolve(name) 修改为更像 resolve(dirPath + name)。
    【解决方案2】:

    使用globnpm 包: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
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2017-09-19
      • 2010-09-05
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 2016-05-20
      相关资源
      最近更新 更多