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

2

6

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/
      [email protected]
      [email protected]
      [email protected]
      [email protected]

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/
      [email protected]

I am looking for function like this:

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

});
Geisha answered 19/5, 2017 at 18:10 Comment(0)
Y
6

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
    }
})
Yvette answered 19/5, 2017 at 19:45 Comment(0)
B
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+/);
Baud answered 19/5, 2017 at 20:15 Comment(1)
This was very helpful to me, I did have to modify the resolve(name) in the unlink to something more like resolve(dirPath + name).Eades
Y
6

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
    }
})
Yvette answered 19/5, 2017 at 19:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.