Skip to content

Instantly share code, notes, and snippets.

@ehsavoie
Created March 28, 2019 09:04
Show Gist options
  • Save ehsavoie/fd1d800f1ac8e7663755e18a3cee3dc4 to your computer and use it in GitHub Desktop.
Save ehsavoie/fd1d800f1ac8e7663755e18a3cee3dc4 to your computer and use it in GitHub Desktop.
Optimize SVG data
var svgToMiniDataURI = require("mini-svg-data-uri");
var fs = require('fs');
var http = require('http');
var https = require('https');
function hasHeader(header, headers) {
var headers = Object.keys(headers || this.headers)
, lheaders = headers.map(function (h) {return h.toLowerCase()})
;
header = header.toLowerCase()
for (var i=0;i<lheaders.length;i++) {
if (lheaders[i] === header) return headers[i]
}
return false
}
const options = {
rejectUnauthorized: false,
// Necessary only if the server's cert isn't for "localhost".
checkServerIdentity: () => { return null; }
};
require('ssl-root-cas')
.inject()
.addFile('/home/ehsavoie/Documents/Red\ Hat/certificates/RH-IT-Root-CA.crt');
const url = process.argv[2];
var client = http;
if (url.startsWith("https")){
client = https;
}
if (url.startsWith("http")) {
client.get(url, options, (res) => {
const {statusCode} = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode} ` + res.headers[hasHeader('location', res.headers)]);
}
if (error) {
console.error(error.message);
// consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => {
rawData += chunk;
});
res.on('end', () => {
try {
var optimizedSVGDataURI = svgToMiniDataURI(rawData);
console.log(optimizedSVGDataURI);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
} else if (url.startsWith("file")) {
console.log(`Processing file: ${url}`);
try {
var optimizedSVGDataURI = svgToMiniDataURI(fs.readFileSync(new URL(url), 'utf-8'));
console.log(optimizedSVGDataURI);
} catch (e) {
console.error(e.message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment