Skip to content

Instantly share code, notes, and snippets.

@cladley
Last active November 27, 2018 10:52
Show Gist options
  • Save cladley/337af6e24356b97729a4edb505e7e9c9 to your computer and use it in GitHub Desktop.
Save cladley/337af6e24356b97729a4edb505e7e9c9 to your computer and use it in GitHub Desktop.
randomise avg ids
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const findIdsRegex = /id="(.+?)"?/ig;
const fileName = process.argv[2];
const fileAbsoluteDirectory = path.dirname(path.resolve(fileName));
let buffer = '';
if (path.extname(fileName) !== '.svg') {
console.log('\x1b[33m%s\x1b[0m', '!!!You need to supply an svg file!!!');
return;
}
const createAbsolutePath = (filename) => {
return path.resolve(fileAbsoluteDirectory, filename);
};
const getNewFilename = (current) => {
current = current.split('.');
current[0] = current[0] + '_CONVERTED';
return current.join('.');
};
const randomLetter = () => {
return String.fromCharCode(97+Math.floor(Math.random() * 26))
}
const stream = fs.createReadStream(fileName, {encoding: 'utf8'});
stream.on('data', data => {
if (data) {
buffer += data;
}
});
stream.on('end', () => {
const convertedSvg = randomizeId(buffer);
createNewSvgFile(convertedSvg);
});
const randomizeId = (svgContents) => {
let result;
const ids = [];
while (result = findIdsRegex.exec(svgContents)) {
let replacementId = crypto.randomBytes(20).toString('hex');
// Place random letter at front because you can't start
// an id with a number
replacementId = randomLetter() + replacementId;
ids.push({
id: result[1],
replacementId: replacementId
});
}
ids.forEach(idObj => {
const idRegex = new RegExp(`id=\"(${idObj.id})\"`, "g");
const r = new RegExp(`xlink:href=\"#(${idObj.id})\"`, "g");
const a = new RegExp(`url\\(#${idObj.id}\\)`, "g");
svgContents = svgContents.replace(idRegex, function(match) {
return `id="${idObj.replacementId}"`;
});
svgContents = svgContents.replace(r, function(match) {
return `xlink:href="#${idObj.replacementId}"`;
});
svgContents = svgContents.replace(a, function(match) {
return `url(#${idObj.replacementId})`;
});
});
return svgContents;
};
const createNewSvgFile = (svgString) => {
const newFilename = createAbsolutePath(getNewFilename(fileName));
fs.writeFile(newFilename, svgString, 'utf8', (err) => {
if (!err) {
console.log('DONE');
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment