Andreas Köberle Andreas Köberle - 5 months ago 58
Node.js Question

Replace a string in a file with nodejs

I use the md5 grunt task to generate MD5 filenames. Now I wanna rename the sources in the html file with the new filename in the callback of the task. I wonder whats the easiest way to do this.

Answer

You could use simple regex:

var result = fileAsString.replace(/string to be replaced/g, 'replacement');

So...

var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/string to be replaced/g, 'replacement');

  fs.writeFile(someFile, result, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});