Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs'),
- path = require('path'),
- dir2read = process.argv[2] || '.',
- config = JSON.parse(fs.readFileSync('_config_.json', 'utf8')),
- escRegExp = /[\^$.*+?()[]{}|]/g,
- hasEscRegExp = RegExp(escRegExp.source);
- const getFiles = (dir) => fs.readdirSync(dir)
- .reduce((files, file) =>
- fs.statSync(path.join(dir, file)).isDirectory() ?
- files.concat(getFiles(path.join(dir, file))) :
- files.concat(path.join(dir, file)),
- []);
- const getFilterdFile = (filePath) => {
- return filePath.endsWith('.chunk.js') || filePath.endsWith('.bundle.js');
- }
- const escapeString = (string) => {
- return hasEscRegExp.test(string) ? string.replace(escRegExp, '\$&') : string;
- }
- const cacheRegExp = (string) => {
- string = string.replace(/^(w)/, '\b$1');
- string = string.replace(/(w)$/, '$1\b');
- return new RegExp(string, 'gm');
- }
- const replaceInFile = (string, find, replace) => {
- for (let key in find) {
- string = string.replace(cacheRegExp(escapeString(find[key])), replace[key]);
- }
- return string;
- }
- try {
- const files = getFiles(dir2read);
- const filteredFiles = files.filter(file => getFilterdFile(file));
- for (const filePath of filteredFiles) {
- try {
- let data = fs.readFileSync(filePath).toString();
- let newData = replaceInFile(data, config.originalConfig, config.replacementConfig);
- if (newData !== data) {
- fs.writeFileSync(filePath, newData);
- console.log(`Matches found`);
- } else {
- console.log(`No matches found`);
- }
- } catch (e) {
- console.log(e);
- }
- }
- console.log(`Replacement complete`);
- } catch (e) {
- console.log(e);
- }
Add Comment
Please, Sign In to add comment