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

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

Delete folder files starting with a word in nodejs

问题

我正在使用nodejs。

嗨,我需要删除以某个单词开头的所有文件夹中的文件。

我尝试了下面的代码,但没有成功:

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));
}
英文:

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

答案1

得分: 1

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

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

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.

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:

确定