javascriptnode.jsreplacegruntjs

Replace a string in a file with nodejs


I use the md5 grunt task to generate MD5 filenames. Now I want to rename the sources in the HTML file with the new filename in the callback of the task. I wonder what's the easiest way to do this.


Solution

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