Last active
June 13, 2024 11:26
-
-
Save leotm/9e188b34419214507e4d to your computer and use it in GitHub Desktop.
Node.js - Find and Replace file(s)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 - 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
How this can be done to
search and replace
in all files into a specify folder? 😎