Skip to content

Instantly share code, notes, and snippets.

@maisui99
Last active August 29, 2015 14:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maisui99/85606793d8b91764d095 to your computer and use it in GitHub Desktop.
Save maisui99/85606793d8b91764d095 to your computer and use it in GitHub Desktop.
css images to base64 and fix ie6/7
/**
* Created with IntelliJ IDEA.
* @author: butian.wth
* @version: 1-0-0
* Date: 14-5-27
* Time: 下午5:23
*/
//new Buffer("Hello World").toString('base64')
var path = require('path');
var fs = require('fs');
var Walker = require('iwalk');
var ignoresList = ['node_modules'];
var reg = /(background:|background-image:)url\((.*?)\)([^;]*?)(}|;}|;.*?})/ig;
function parse(filename) {
var text = fs.readFileSync(filename).toString();
var matched;
var list = [];
while ((matched = reg.exec(text))) {
//console.log(matched[2]);
if (matched[2].indexOf('images') >= 0) {
list.push({
origin: matched[0],
backgroundType: matched[1],
item: matched[2].trim(),
afterUrl: matched[3],
afterBackground: matched[4],
filename: filename,
index: matched.index
});
}
}
list.forEach(function (item) {
var ext = path.extname(item.item).replace('.','');
item.picFile = fs.readFileSync('./src/' + item.item);
item.base64 = new Buffer(item.picFile).toString('base64');
item.base64 = 'data:image/' + ext + ';base64,' + item.base64;
text = text.replace(item.origin, item.backgroundType + 'url(' + item.base64 + ')' + item.afterUrl + ';' + '*background-image:url(' + item.item + ');' + item.afterBackground);
});
//console.log(text);
fs.writeFileSync(filename, text);
return list;
};
var list = [];
var walker = new Walker();
var ignoresReg = new RegExp('\/(' + ignoresList.join('|') + ')\/', "ig");
walker.on('file', function (filename) {
if (filename.match(ignoresReg)) {
return;
}
var ext = path.extname(filename);
if (ext === '.css') {
list = list.concat(parse(filename));
}
console.log('base64转换成功');
});
walker.on('error', function (err) {
walker.removeAllListeners('error');
console.log('stop by error!!');
});
walker.on('end', function () {
});
walker.walk('./build');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment