Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
base64 encoding images in NodeJS
* Complete reworking of JS from
* Removes external `request` dependency
* Caveats:
* * No error checking
* * Largely a POC. `data` URI is accurate, but this code cannot simply be inserted into an `express` app
var URL = require('url'),
sURL = '',
oURL = URL.parse(sURL),
http = require('http'),
client = http.createClient(80, oURL.hostname),
request = client.request('GET', oURL.pathname, {'host': oURL.hostname})
request.on('response', function (response)
var type = response.headers["content-type"],
prefix = "data:" + type + ";base64,",
body = "";
response.on('end', function () {
var base64 = new Buffer(body, 'binary').toString('base64'),
data = prefix + base64;
response.on('data', function (chunk) {
if (response.statusCode == 200) body += chunk;

Cool, this is the first example of doing this I've found that works. Thanks!


Thanks a lot for this code ! Save me many time !


Thanks a lot for this code ! Save me many time too!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.