Guest User

Untitled

a guest
Oct 20th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. const fs = require('fs'),
  2. path = require('path'),
  3. dir2read = process.argv[2] || '.',
  4. config = JSON.parse(fs.readFileSync('_config_.json', 'utf8')),
  5. escRegExp = /[\^$.*+?()[]{}|]/g,
  6. hasEscRegExp = RegExp(escRegExp.source);
  7.  
  8. const getFiles = (dir) => fs.readdirSync(dir)
  9. .reduce((files, file) =>
  10. fs.statSync(path.join(dir, file)).isDirectory() ?
  11. files.concat(getFiles(path.join(dir, file))) :
  12. files.concat(path.join(dir, file)),
  13. []);
  14.  
  15. const getFilterdFile = (filePath) => {
  16. return filePath.endsWith('.chunk.js') || filePath.endsWith('.bundle.js');
  17. }
  18.  
  19. const escapeString = (string) => {
  20. return hasEscRegExp.test(string) ? string.replace(escRegExp, '\$&') : string;
  21. }
  22.  
  23. const cacheRegExp = (string) => {
  24. string = string.replace(/^(w)/, '\b$1');
  25. string = string.replace(/(w)$/, '$1\b');
  26. return new RegExp(string, 'gm');
  27. }
  28.  
  29. const replaceInFile = (string, find, replace) => {
  30. for (let key in find) {
  31. string = string.replace(cacheRegExp(escapeString(find[key])), replace[key]);
  32. }
  33. return string;
  34. }
  35.  
  36. try {
  37. const files = getFiles(dir2read);
  38. const filteredFiles = files.filter(file => getFilterdFile(file));
  39. for (const filePath of filteredFiles) {
  40. try {
  41. let data = fs.readFileSync(filePath).toString();
  42. let newData = replaceInFile(data, config.originalConfig, config.replacementConfig);
  43. if (newData !== data) {
  44. fs.writeFileSync(filePath, newData);
  45. console.log(`Matches found`);
  46. } else {
  47. console.log(`No matches found`);
  48. }
  49. } catch (e) {
  50. console.log(e);
  51. }
  52. }
  53. console.log(`Replacement complete`);
  54. } catch (e) {
  55. console.log(e);
  56. }
Add Comment
Please, Sign In to add comment