Creating Base64 Encoded String from an Image in Node.js

Voice of Reason
Code Complete
Published in
2 min readAug 13, 2015

I’ve been writing a lot of MEAN (MongoDb, Express, AngularJS and Express) code lately and the latest in the series of hurdles I’ve been able to cross of recent has been generating the Base64 encoded version of an image file.

I had just added a new endpoint to an API I was working on and it included photos of users. For the web app, I was happy to just get the url of the photo and have the browser request it when needed but the API consumers (Android and iOS mobile devs) thought differently. The wanted to have the image as a base64 encoded string and so I reached out to Google.

Using this StackOverflow question and answer as my base, this is the function I eventually arrived at:

function encodeImage(imageUrl, callback) {
var URL = require('url'),
sURL = imageUrl,
oURL = URL.parse(sURL),
http = require('http'),
request = http.request({method:'GET', path:oURL.pathname, host: oURL.hostname, port:80});
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;
return callback(data);
});
response.on('data', function (chunk) {
if (response.statusCode == 200) body += chunk;
});
});
}
It should be noted that there are a few differences between my solution and that on StackOverflow.
  • First, I’ve created a function which expects a callback.
  • Secondly, line 6 makes use of http.request instead of http.createClient and client.request . This is because http.createClient has been deprecated in my version of Express (4.0.0)

--

--

Voice of Reason
Code Complete

Speaking from underneath my programmer’s hat… behind an observer’s desk