Last active
August 29, 2015 14:17
-
-
Save jamesasu/dc6a3a3004bba9f7bbf0 to your computer and use it in GitHub Desktop.
How to create inline JavaScript lazypipe function for custom file processing
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 collapseSrc = function(file) { | |
return lazypipe() | |
.pipe(function(){ | |
return through.obj(function(file, enc, cb) { | |
var contentTypes = { | |
".png": "image/png", | |
".gif": "image/gif", | |
".jpg": "image/jpeg", | |
".jpeg": "image/jpeg", | |
".bmp": "image/bmp", | |
".webp": "image/webp" | |
}; | |
var base = process.cwd()+'/dist'; | |
if (file.isStream()) { | |
console.warn('Streams not supported!'); | |
return cb(); | |
} | |
if (file.isBuffer()) { | |
try { | |
var dom = cheerio.load(String(file.contents)); | |
var styles = []; | |
dom('img').each(function(idx, el) { | |
el = dom(el); | |
var src = el.attr('src'); | |
if (src && !url.parse(src).hostname) { | |
var filepath = base + '/' + src; | |
var ext = filepath.match(/\.[a-z0-9]+$/i); | |
var img = fs.readFileSync(filepath); | |
var contentType = contentTypes[ext] || 'image/png'; | |
var dataUri = "data:" + contentType + ";base64," + img.toString("base64"); | |
el.attr('src', dataUri); | |
} | |
}); | |
dom('source').each(function(idx, el) { | |
el = dom(el); | |
var src = el.attr('srcset'); | |
if (src && !url.parse(src).hostname) { | |
var filepath = base + '/' + src.match(/^[^\s]+/i); | |
var multiplier = src.match(/[^\s]+$/i); | |
var ext = filepath.match(/\.[a-z0-9]+$/i); | |
var img = fs.readFileSync(filepath); | |
var contentType = contentTypes[ext] || 'image/png'; | |
var dataUri = "data:" + contentType + ";base64," + img.toString("base64") + ' ' + multiplier; | |
el.attr('srcset', dataUri); | |
} | |
}); | |
file.contents = new Buffer(dom.html({decodeEntities: false})); | |
this.push(file); | |
return cb(null, file); | |
} catch(e) { | |
console.warn(e.message); | |
return cb(); | |
} | |
} | |
return cb(null, file); //no-op | |
}); | |
})(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment