-1

I am using nodejs.

Hi, I need to delete all files starting with a word in a folder.

I have tried the next code but no look:

const deleteFile = (path, regex) => {
  fs.readdirSync(path)
    .filter(f => regex.test(f))
    .map(f => fs.unlinkSync(path + f));
};

const starting_filename="name_to_delete";

if (tenantInstance.companyLogoUrl) {
    const path = join(__dirname, "..", "..", "..", "public");
    const regex = `/^${starting_filename}+/`;
    deleteFile(path, new RegExp(regex));
  }
 
Luiz Alves
  • 2,575
  • 4
  • 34
  • 75

1 Answers1

1

Slashes are part of the syntax of RegExp literals, you don't wrap them around the string when using new RegExp() -- that will try to match literal slash characters.

You don't need + at the end of the RegExp. That matches 1 or more of the last character of starting_filename. This is redundant when you're using test() rather than match(), since it doesn't matter how far the match reaches.

const regex = `^${starting_filename}`;

Note that this will not work if starting_filename contains any characters that have special meaning in a regular expression, they need to be escaped. See How to escape regular expression special characters using javascript?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Sorry, But is deleting only one file starting with the name. Other files stay in the folder. – Luiz Alves Jun 15 '23 at 22:52
  • This is what I did: const deleteFile = (path, regex) => { fs.readdirSync(path) .filter(f => regex.test(f)) .map(f => { console.log(`${path}/${f}`); return fs.unlinkSync(`${path}/${f}`); }); }; and const regex = `^${starting_filename}`; – Luiz Alves Jun 15 '23 at 22:54
  • Does it show all the filenames in `console.log()`? – Barmar Jun 15 '23 at 23:00
  • There's no need to return anything, since you're not doing anything with the returned values. And you should use `forEach()` instead of `map()` since you don't use the returned array. – Barmar Jun 15 '23 at 23:00
  • My bad. It´s working. Thank you – Luiz Alves Jun 15 '23 at 23:10