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

2 Answers 2

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+/); 
Sign up to request clarification or add additional context in comments.

1 Comment

This was very helpful to me, I did have to modify the resolve(name) in the unlink to something more like resolve(dirPath + name).
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 } }) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.