Skip to content

Instantly share code, notes, and snippets.

@stephen-james
Created March 11, 2015 15:27
Show Gist options
  • Save stephen-james/6192aaf94bbe3d10da10 to your computer and use it in GitHub Desktop.
Save stephen-james/6192aaf94bbe3d10da10 to your computer and use it in GitHub Desktop.
svg-cleaner.js
var fs = require('fs');
var path = require('path');
// validate args
if (process.argv.length < 3) {
console.log('usage:');
console.log('\tnode svg-cleaner.js <path>')
return;
}
var pathToRead = path.resolve(process.cwd(), process.argv[2]);
var svgElementEx = /(<svg[^>]*>)/g;
function cleanFile(file) {
var filePath = path.resolve(pathToRead, file);
fs.readFile(filePath, undefined, function(err, data) {
var svgElementText;
var styleAttributes;
var styleAttributeEx = /style=(".*?"|'.*?'|[^"'][^\s]*)/gm;
var st0StyleEx = /(.st0(?:\s*){(?:[^}]*)})/gm;
var styles = [];
var cleanSvgData = data.toString();
var cleanSvgElement;
var styleBlock;
if (err) {
return console.log('error reading file: ', file, err);;
}
// clean inline style block, remove forgotten .st0 class styles
cleanSvgData = cleanSvgData.replace(st0StyleEx, '');
// clean svg element - duplicate style attributes
svgElementText = svgElementEx.exec(data);
if (svgElementText && svgElementText.length) {
svgElementText = svgElementText[0];
while ((styleAttributes = styleAttributeEx.exec(svgElementText)) !== null) {
styles.push(styleAttributes[1]);
}
if (styles.length > 1) {
// merge styles
var mergedStyles = '';
styles.forEach(function(style) {
mergedStyles += style.substring(1, style.length - 2);
if (mergedStyles.substring(mergedStyles.length - 1, 1) !== ';') {
mergedStyles += ';';
}
});
cleanSvgElement = svgElementText;
cleanSvgElement = cleanSvgElement.replace(styleAttributeEx, '');
cleanSvgElement = cleanSvgElement.slice(0, cleanSvgElement.length - 1) +
' style="' + mergedStyles + '"' +
'>';
cleanSvgData = cleanSvgData.replace(svgElementEx, cleanSvgElement);
}
}
if (cleanSvgData !== data.toString()) {
fs.writeFile(filePath, cleanSvgData, null, function(err) {
if (err) {
return console.log('unable to save ', filePath, err);
}
console.log('cleaned: ' + filePath);
});
}
});
}
function fixFiles(err, files) {
files.forEach(function(file) {
if (file.substring(file.length - 4) === '.svg') {
cleanFile(file);
}
});
}
fs.readdir(pathToRead, fixFiles);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment