Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs');
- const proc = require('process');
- const path = require('path');
- function modifyUrl(content, depth) {
- let replacementArray = [];
- for (let i = 0; i < depth; i++) {
- replacementArray.push('..');
- }
- let replacement = replacementArray.join('/');
- if (replacementArray.length > 0) {
- replacement = `${replacement}/`;
- }
- return content.replace(/url\("\//gm, `url("${replacement}`)
- .replace(/url\('\//gm, `url('${replacement}`)
- .replace(/url\(\//gm, `url(${replacement}`)
- }
- function convertToRelativeFilePaths(directory, depth = 0, extensionRegex = /^\.css$/) {
- fs.readdir(directory, (error, files) => {
- if (error) {
- console.error(`Unable to list directory ${directory}`, error);
- proc.exit(1)
- }
- files.forEach((file, index) => {
- let absolutePath = path.join(directory, file);
- fs.stat(absolutePath, (error, stat) => {
- if (error) {
- console.error(`Unable to stat path ${absolutePath}`, error);
- return
- }
- if (stat.isFile()) {
- let extension = path.extname(absolutePath);
- if (!extensionRegex.test(extension)) {
- return
- }
- console.debug(`Processing file ${absolutePath}`);
- fs.readFile(absolutePath, 'utf8', (error, data) => {
- if (error) {
- console.error(`Unable to read file ${absolutePath}`, error);
- return
- }
- let result = modifyUrl(data, depth);
- fs.writeFile(absolutePath, result, error => {
- if (error) {
- console.error(error)
- }
- });
- });
- } else if (stat.isDirectory()) {
- convertToRelativeFilePaths(absolutePath, depth + 1)
- } else {
- console.warn(`Unknown file stat for ${absolutePath}`)
- }
- });
- });
- });
- }
- // call like `node relativateCssUrls.js out`
- convertToRelativeFilePaths(proc.argv[2]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement