Skip to content

Instantly share code, notes, and snippets.

@speier
Created May 4, 2012 14:04
Show Gist options
  • Save speier/2594980 to your computer and use it in GitHub Desktop.
Save speier/2594980 to your computer and use it in GitHub Desktop.
Replace CSS images with inline base64 data
var fs = require('fs');
var path = require('path');
function cssIncImages(cssFile) {
var imgRegex = /url\s?\(['"]?(.*?)(?=['"]?\))/gi;
var css = fs.readFileSync(cssFile, 'utf-8');
while (match = imgRegex.exec(css)) {
var imgPath = path.join(path.dirname(cssFile), match[1]);
try {
var img = fs.readFileSync(imgPath, 'base64');
var ext = imgPath.substr(imgPath.lastIndexOf('.') + 1);
css = css.replace(match[1], 'data:image/' + ext + ';base64,' + img);
} catch (err) {
console.log('Image not found (%s).', imgPath);
}
}
// fs.writeFileSync(cssFile, css, 'utf-8'); // you can overwrite the original file with this line
return css;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment