Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
var express = require('express'),
request = require('request'),
BufferList = require('bufferlist').BufferList,
sys = require('sys');
var app = express.createServer(
app.get('/', function(req, res){
if(req.param("url")) {
var url = unescape(req.param("url"));
var bl = new BufferList();
request({uri:url, responseBodyStream: bl}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data_uri_prefix = "data:" + response.headers["content-type"] + ";base64,";
var image = new Buffer(bl.toString(), 'binary').toString('base64');
image = data_uri_prefix + image;
res.send('<img src="'+image+'"/>');

jfsiii commented Jan 30, 2011

I saw this answer on

My question and failure symptoms are the same as the original poster, but I cannot get this gist to work. I simply end up with data:image/png;base64,. If I console.log(body.length) I get 0.

I've re-factored this slightly at My results are the same as this gist. I just wanted one which didn't depend on express so I could easily test in the node REPL.

Do you have any idea what I'm doing wrong or what I can do to get this working as intended?


bxjx commented Jan 31, 2011

I'm running node 2.0 and I ran with your gist with the slight change of:

 console.log('<img src="'+data+'"/>');

...and then ran: node img2data.js > test.html
When i opened test.html it loaded the image just fine.

hmm... body might not be reliable here as you're passing in the buffer. Try to debug the contents of the buffer. Let me know how you go.

jfsiii commented Jan 31, 2011

I'm running 0.2.5 and get the same results whether using body or bl. If I'm reading correctly, body should be the value passed to responseBodyStream, right?

Here's my experience:

I've now discovered that a second request call will allow the script to work as expected. My first thought was "race condition" or "async issue", even though I couldn't see any issues, but I using setTimeouts to delay the first request by 2 or 5 seconds didn't change anything.

I'm pretty sure the issue is on my end (at least two other people are successful) and I don't want to burden you with debugging via gist. Any general pointers on narrowing down the issue, or docs to using/debugging Buffers & BufferLists would be appreciated.

jfsiii commented Jan 31, 2011

Take a look at

I ditched the external dependencies (BufferList and request) and was able to encode the image using only the standard HTTP and URL modules

While I'm curious what I was doing wrong, I'm happier with this approach. Let me know if you see any areas for improvement. Specifically, how I can skip the step of assembling the binary string and jump straight to converting it to base64.

this should work fine

the current example above doesn't work due to dericated modules in the request

try by putting


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