Last active
November 22, 2015 19:30
-
-
Save vdavez/1881af6b9bb439ac6abd to your computer and use it in GitHub Desktop.
Inline imgs to markdown
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'); | |
// Read file passed in command line args | |
var f = fs.readFileSync(process.argv[2],'utf8'); | |
// Replace markdown img regex with <img> with base64 data uri & pipe to stdout | |
var re =/!\[\]\(([^]*?)\)/g; | |
process.stdout.write(f.replace(re, replaceImagesWithBase64)); | |
/** | |
* Helper function to replace a markdown img with <img> tag with data uri | |
* @param {string} match the markdown img | |
* @param {string} p1 the filename of the img src | |
* @returns {string} the converted <img> tag with data uri | |
*/ | |
function replaceImagesWithBase64(match, p1) { | |
return ( | |
// Check the filename to see if it's a URL, and if so, ignore it | |
p1.substr(0,4) === "http" ? match : | |
// Otherwise, it's a local file that should be replaced with base64 encoding | |
"<img src='data:image/png;base64," + fs.readFileSync(p1,'base64') + "'/>" | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment