Created
May 4, 2012 14:04
-
-
Save speier/2594980 to your computer and use it in GitHub Desktop.
Replace CSS images with inline base64 data
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
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