Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. const fs = require('fs');
  2. const proc = require('process');
  3. const path = require('path');
  4.  
  5. function modifyUrl(content, depth) {
  6. let replacementArray = [];
  7. for (let i = 0; i < depth; i++) {
  8. replacementArray.push('..');
  9. }
  10. let replacement = replacementArray.join('/');
  11. if (replacementArray.length > 0) {
  12. replacement = `${replacement}/`;
  13. }
  14. return content.replace(/url\("\//gm, `url("${replacement}`)
  15. .replace(/url\('\//gm, `url('${replacement}`)
  16. .replace(/url\(\//gm, `url(${replacement}`)
  17. }
  18.  
  19. function convertToRelativeFilePaths(directory, depth = 0, extensionRegex = /^\.css$/) {
  20. fs.readdir(directory, (error, files) => {
  21. if (error) {
  22. console.error(`Unable to list directory ${directory}`, error);
  23. proc.exit(1)
  24. }
  25.  
  26. files.forEach((file, index) => {
  27. let absolutePath = path.join(directory, file);
  28.  
  29. fs.stat(absolutePath, (error, stat) => {
  30. if (error) {
  31. console.error(`Unable to stat path ${absolutePath}`, error);
  32. return
  33. }
  34. if (stat.isFile()) {
  35. let extension = path.extname(absolutePath);
  36. if (!extensionRegex.test(extension)) {
  37. return
  38. }
  39. console.debug(`Processing file ${absolutePath}`);
  40. fs.readFile(absolutePath, 'utf8', (error, data) => {
  41. if (error) {
  42. console.error(`Unable to read file ${absolutePath}`, error);
  43. return
  44. }
  45. let result = modifyUrl(data, depth);
  46. fs.writeFile(absolutePath, result, error => {
  47. if (error) {
  48. console.error(error)
  49. }
  50. });
  51. });
  52. } else if (stat.isDirectory()) {
  53. convertToRelativeFilePaths(absolutePath, depth + 1)
  54. } else {
  55. console.warn(`Unknown file stat for ${absolutePath}`)
  56. }
  57. });
  58. });
  59. });
  60. }
  61.  
  62. // call like `node relativateCssUrls.js out`
  63. convertToRelativeFilePaths(proc.argv[2]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement