Node.js get image from web and encode with base64

Aleksr9 picture Aleksr9 · Jun 15, 2013 · Viewed 88.8k times · Source

I'm trying to fetch an image from the web and encode it with base64.

what i have so far is basically:

var request = require('request');
var BufferList = require('bufferlist').BufferList;

bl = new BufferList(),

request({uri:'http://tinypng.org/images/example-shrunk-8cadd4c7.png',responseBodyStream: bl}, function (error, response, body) 
{
    if (!error && response.statusCode == 200) 
    {
        var type = response.headers["content-type"];
        var prefix = "data:" + type + ";base64,";
        var base64 = new Buffer(bl.toString(), 'binary').toString('base64');
        var data = prefix + base64;
        console.log(data);
    }
});

This seems to be pretty close to the solution but i can't quite get it to work. It recognizes the data type and gives out the output:

data:image/png;base64

however the bufferlist 'bl' seems to be empty.

Thanks in advance!

Answer

Dan Kohn picture Dan Kohn · Jun 16, 2013

BufferList is obsolete, as its functionality is now in Node core. The only tricky part here is setting request not to use any encoding:

var request = require('request').defaults({ encoding: null });

request.get('http://tinypng.org/images/example-shrunk-8cadd4c7.png', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        data = "data:" + response.headers["content-type"] + ";base64," + Buffer.from(body).toString('base64');
        console.log(data);
    }
});