javascriptnode.jsfswritefileappendfile

Replace a line in txt file using JavaScript


I am trying to simply replace a line in a text file using JavaScript.

The idea is:

var oldLine = 'This is the old line';
var newLine = 'This new line replaces the old line';

Now i want to specify a file, find the oldLine and replace it with the newLine and save it.

Anyone who can help me here?


Solution

  • This should do it

    var fs = require('fs')
    fs.readFile(someFile, 'utf8', function (err,data) {
    
      var formatted = data.replace(/This is the old line/g, 'This new line replaces the old line');
    
     fs.writeFile(someFile, formatted, 'utf8', function (err) {
        if (err) return console.log(err);
     });
    });