Skip to content

Instantly share code, notes, and snippets.

@vdavez
Last active November 22, 2015 19:30
Show Gist options
  • Save vdavez/1881af6b9bb439ac6abd to your computer and use it in GitHub Desktop.
Save vdavez/1881af6b9bb439ac6abd to your computer and use it in GitHub Desktop.
Inline imgs to markdown
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