删除以一个单词开头的文件夹文件在Node.js中

huangapple go评论89阅读模式
英文:

Delete folder files starting with a word in nodejs

问题

  1. 我正在使用nodejs
  2. 嗨,我需要删除以某个单词开头的所有文件夹中的文件。
  3. 我尝试了下面的代码,但没有成功:
  4. const deleteFile = (path, regex) => {
  5. fs.readdirSync(path)
  6. .filter(f => regex.test(f))
  7. .map(f => fs.unlinkSync(path + f));
  8. };
  9. const starting_filename="name_to_delete";
  10. if (tenantInstance.companyLogoUrl) {
  11. const path = join(__dirname, "..", "..", "..", "public");
  12. const regex = /^${starting_filename}+/;
  13. deleteFile(path, new RegExp(regex));
  14. }
英文:

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:

  1. const deleteFile = (path, regex) => {
  2. fs.readdirSync(path)
  3. .filter(f => regex.test(f))
  4. .map(f => fs.unlinkSync(path + f));
  5. };
  6. const starting_filename="name_to_delete";
  7. if (tenantInstance.companyLogoUrl) {
  8. const path = join(__dirname, "..", "..", "..", "public");
  9. const regex = `/^${starting_filename}+/`;
  10. deleteFile(path, new RegExp(regex));
  11. }

答案1

得分: 1

斜杠是正则表达式字面量语法的一部分,在使用 new RegExp() 时不需要将它们包裹在字符串中——这将尝试匹配字面斜杠字符。

在正则表达式的末尾不需要使用 +。这会匹配 starting_filename 的最后一个字符的一个或多个。当你使用 test() 而不是 match() 时,这是多余的,因为匹配的达到程度无关紧要。

  1. const regex = `^${starting_filename}`;

请注意,如果 starting_filename 包含任何在正则表达式中具有特殊含义的字符,它们需要进行转义。请参考 https://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript

英文:

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.

  1. 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 https://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript

huangapple
  • 本文由 发表于 2023年6月16日 06:31:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76485883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定