Andreas Köberle Andreas Köberle - 1 year ago 169
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 Source

You could use simple regex:

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


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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download