Skip to content

Instantly share code, notes, and snippets.

@leotm
Last active March 22, 2022 13:37
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save leotm/9e188b34419214507e4d to your computer and use it in GitHub Desktop.
Save leotm/9e188b34419214507e4d to your computer and use it in GitHub Desktop.
Node.js - Find and Replace file(s)
var glob = require('glob');
var fs = require('fs');
var replace = require('replace');
// Find file(s)
glob('fileName.txt', function(err, files) {
if (err) { throw err; }
files.forEach(function(item, index, array) {
console.log(item + ' found');
// Read file
console.log(fs.readFileSync(item, 'utf8'));
// Find and Replace string
replace({
regex: 'original string',
replacement: 'replacement string',
paths: [item],
recursive: true,
silent: true
});
console.log('Replacement complete');
// Read file
console.log(fs.readFileSync(item, 'utf8'));
});
});
@AlonsoK28
Copy link

How this can be done to search and replace in all files into a specify folder? 😎

@justindonnaruma
Copy link

@AlonsoK28 - change filename.txt to ./* for all in a current directory, or <directoryName>/* for a directory relative to your current working directory.
See Glob on NPM for more details

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment