Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
base64 encoding images in NodeJS
/*
* Complete reworking of JS from https://gist.github.com/803410
* 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 = 'http://nodejs.org/logo.png',
oURL = URL.parse(sURL),
http = require('http'),
client = http.createClient(80, oURL.hostname),
request = client.request('GET', oURL.pathname, {'host': oURL.hostname})
;
request.end();
request.on('response', function (response)
{
var type = response.headers["content-type"],
prefix = "data:" + type + ";base64,",
body = "";
response.setEncoding('binary');
response.on('end', function () {
var base64 = new Buffer(body, 'binary').toString('base64'),
data = prefix + base64;
console.log(data);
});
response.on('data', function (chunk) {
if (response.statusCode == 200) body += chunk;
});
});
@xaptronic

This comment has been minimized.

Show comment Hide comment
@xaptronic

xaptronic Sep 25, 2011

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

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

@egwada

This comment has been minimized.

Show comment Hide comment
@egwada

egwada Aug 29, 2013

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

egwada commented Aug 29, 2013

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

@jerryni

This comment has been minimized.

Show comment Hide comment
@jerryni

jerryni Oct 14, 2014

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

jerryni commented Oct 14, 2014

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

@onggiaze

This comment has been minimized.

Show comment Hide comment
@onggiaze

onggiaze Nov 23, 2016

This helps me as well. Thank you for this code.

This helps me as well. Thank you for this code.

@anywhere3d

This comment has been minimized.

Show comment Hide comment
@anywhere3d

anywhere3d Nov 7, 2017

It is a piece of art. Thank you.

It is a piece of art. Thank you.

@armatusmiles

This comment has been minimized.

Show comment Hide comment
@armatusmiles

armatusmiles Mar 7, 2018

Nice, thanks.

Nice, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment