Created
January 31, 2011 15:54
-
-
Save jfsiii/804225 to your computer and use it in GitHub Desktop.
base64 encoding images in NodeJS
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
/* | |
* 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; | |
}); | |
}); |
Thanks a lot for this code ! Save me many time !
Thanks a lot for this code ! Save me many time too!
This helps me as well. Thank you for this code.
It is a piece of art. Thank you.
Nice, thanks.
23 line save me, thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool, this is the first example of doing this I've found that works. Thanks!