Created
November 23, 2011 15:29
-
-
Save garth/1388969 to your computer and use it in GitHub Desktop.
Convert url image ref into inline base 64 in css with nodejs
This file contains hidden or 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 css = 'insert lots of css here'; | |
var files = {}; | |
css = css.replace(/url\((\S*)\.(png|jpg|jpeg|gif)\)/g, function(match, file, type) | |
{ | |
var fileName = file + '.' + type; | |
var size = fs.statSync(fileName).size; | |
if (size > 4096) { | |
console.log('Skipping ' + fileName + ' (' + (Math.round(size/1024*100)/100) + 'k)'); | |
return match; | |
} | |
else { | |
var base64 = fs.readFileSync(fileName).toString('base64'); | |
if (typeof(files[fileName]) !== 'undefined') { | |
console.log('Warning: ' + fileName + ' has already been base64 encoded in the css'); | |
} | |
files[fileName] = true; | |
return 'url("data:image/' + (type === 'jpg' ? 'jpeg' : type) + ';base64,' + base64 + '")'; | |
} | |
}); |
https://gist.github.com/4437292
Edited to allow for single or double quotes:
css = css.replace(/url\(["']?(\S*)\.(png|jpg|jpeg|gif)["']?\)/g, function(match, file, type)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much for this post 'garth', here is an example with Lessjs:
If it can help;)