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

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

Perhaps the "replace" module (www.npmjs.org/package/replace) also would work for you. It would not require you to read and then write the file.

Adapted from the documentation:

// install:

npm install replace 

// require:

var replace = require("replace");

// use:

replace({
    regex: "string to be replaced",
    replacement: "replacement string",
    paths: ['path/to/your/file'],
    recursive: true,
    silent: true,
});

You can also use the 'sed' function that's part of ShellJS ...

 $ npm install [-g] shelljs


 require('shelljs/global');
 sed('-i', 'search_pattern', 'replace_pattern', file);

Visit ShellJs.org for more examples.

Since replace wasn't working for me, I've created a simple npm package replace-in-file to quickly replace text in one or more files. It's partially based on @asgoth's answer.

To install:

npm install replace-in-file

To use:

//Require module
var replace = require('replace-in-file');

//Replace "Find me" in a single file
replace('path/to/file', /Find\sme/g, 'Replacement', cb);

//Replace "Find me" in a several files
replace([
  'path/to/file',
  'path/to/other/file',
], /Find\sme/g, 'Replacement', cb);