5

I want to delete all files that there file names start with the same string in a certain directory, for example I have the following directory:

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

so I would like to apply a function to delete all the files that start with the string profile-photo to have at the end the following directory:

public/
      cover-photo-KAS@hu9.png

I am looking for function like this:

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

});
Oded Ben Dov
  • 9,936
  • 6
  • 38
  • 53
Karim
  • 198
  • 1
  • 10

2 Answers2

7

As Sergey Yarotskiy mentioned, using a package like glob would probably be ideal since that package is already tested and would make filtering files much easier.

That being said, the general algorithmic approach you can take is:

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+/);
Community
  • 1
  • 1
nem035
  • 34,790
  • 6
  • 87
  • 99
  • 2
    This was very helpful to me, I did have to modify the resolve(name) in the unlink to something more like resolve(dirPath + name). – Josh May 11 '18 at 19:40
5

Use glob npm package: 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
  • 4,536
  • 2
  • 19
  • 27