Andreas Köberle Andreas Köberle - 4 months ago 37
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.


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