Om3ga
Om3ga

Reputation: 32843

remove a string from a file using nodejs

I am trying to remove a string from text.txt. text.txt file contains following format of string

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

Now what I am doing is watching a folder and when any of the above listed file, lets say text/about.txt, is deleted then text.txt file should automatically be updated to following

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

For this I am using hound module to keep watching for delete event. And replace module to replace deleted path from text.txt file. Below is my code

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

});

But my above code does not remove particular string i.e. file from text.txt file. How can I solve this?

UPDATE

file in above code has this value text/about.txt.

Upvotes: 0

Views: 1354

Answers (2)

antimatter
antimatter

Reputation: 3480

This is a error in semantics, you misinterpreted what happens when you do this:

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

Here, file in the RegExp object is looking for a string called file, not the actual variable contents of the String object you're passing into the function. Do this instead:

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

See RegExp for more details.

Upvotes: 1

Varun Chakervarti
Varun Chakervarti

Reputation: 1042

I have updated variable search_content and replace_content to handle special characters also and then using fs module to replace all strings in a file. Also you can run a synchronous loop on a files to replace strings using callbacks.

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

Upvotes: 1

Related Questions