使用 NodeJS 从文件中删除字符串

remove a string from a file using nodejs

本文关键字:删除 字符串 文件 NodeJS 使用      更新时间:2023-09-26

我正在尝试从text.txt中删除字符串。 text.txt文件包含以下格式的字符串

text/more/more.txt
text/home.txt
text/more/yoo/yoo.txt
text/about.txt

现在我正在做的是监视一个文件夹,当上面列出的任何文件(例如text/about.txt)被删除时text.txt该文件应自动更新为以下内容

text/more/more.txt
text/home.txt
text/more/yoo/yoo.txt

为此,我正在使用hound模块来监视删除事件。并replace模块来替换text.txt文件中已删除的路径。下面是我的代码

watcher.on('delete', function(file, stats) {
    replace({
        regex: /file/g, // file is something like this text/about.txt
        replacement: '',
        paths: [path + '/text.txt'],
        recursive: true,
        silent: true,
    });
});

但是我上面的代码不会删除特定的字符串,即 从text.txt文件中file我该如何解决这个问题?

更新

上面的代码中的file具有此值text/about.txt

这是语义上的错误,你误解了这样做时会发生什么:

watcher.on('delete', function(file, stats) {
    ...
    regex: /file/g, // file is something like this text/about.txt
    ...
}

在这里,RegExp 对象中的file是查找一个名为 file 的字符串,而不是您传递给函数的 String 对象的实际变量内容。请改为执行以下操作:

    regex: new RegExp(file, 'g'), // file is something like this text/about.txt

有关更多详细信息,请参阅正则表达式。

我已经更新了变量search_contentreplace_content来处理特殊字符,然后使用 fs 模块替换文件中的所有字符串。还可以对文件运行同步循环,以使用回调替换字符串。

// Require fs module here.
var search_content = "file";
var replace_content = '';
var source_file_path = '<<source file path where string needs to be replaced>>';
search_content = search_content.replace(/([.?&;*+^$[']''(){}|-])/g, "''$1");//improve
search_content = new RegExp(search_content, "g");
fs.readFile(source_file_path, 'utf8', function (rfErr, rfData) {
    if (rfErr) {
        // show error
    }
    var fileData = rfData.toString();
    fileData = fileData.replace(search_content, replace_content);
    fs.writeFile(source_file_path, fileData, 'utf8', function (wfErr) {
        if (wfErr) {
            // show error
        }
        // callback goes from here
    });
});