Last active
November 27, 2018 10:52
-
-
Save cladley/337af6e24356b97729a4edb505e7e9c9 to your computer and use it in GitHub Desktop.
randomise avg ids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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