Skip to content

Instantly share code, notes, and snippets.

@hakobera
Forked from jfsiii/img2data.js
Created May 8, 2011 17:16
Show Gist options
  • Save hakobera/961513 to your computer and use it in GitHub Desktop.
Save hakobera/961513 to your computer and use it in GitHub Desktop.
base64 encoding images using express in NodeJS
/*
* node-dataurl-proxy
*
* This code can run in Clound Foundry (http://cloudfoundry.com)
* You can see example: http://dataurlproxy.cloudfoundry.com/?url=[url]
*/
require.paths.unshift('./node_modules');
var express = require('express'),
URL = require('url'),
http = require('http');
var app = module.exports = express.createServer(),
port = process.env.VMC_APP_PORT || 3000;
// Configuration
app.configure(function(){
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', function(req, res){
var url, client, proxyRequest;
if (req.param('url')) {
url = URL.parse(req.param('url'));
client = http.createClient(80, url.hostname);
client.on('error', function(err) {
res.statusCode = 404;
res.send(err.message);
});
proxyRequest = client.request('GET', url.pathname, { "host": url.hostname });
proxyRequest.end();
proxyRequest.on('response', function(proxyResponse) {
var type = proxyResponse.header('content-type'),
prefix = 'data:' + type + ';base64,',
body = '',
success = true;
proxyResponse.setEncoding('binary');
proxyResponse.on('data', function(chunk) {
if (proxyResponse.statusCode === 200) {
body += chunk;
} else {
res.statusCode = proxyResponse.statusCode;
body += chunk;
success = false;
}
});
proxyResponse.on('end', function() {
if (success) {
var base64 = new Buffer(body, 'binary').toString('base64'),
data = prefix + base64,
obj = {
"src": url.href,
"data": data
};
res.contentType('application/json');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET,POST");
res.send(JSON.stringify(obj));
} else {
res.send(body);
}
});
});
}
});
// Only listen on $ node app.js
if (!module.parent) {
app.listen(port);
console.log("Express server listening on port %d", app.address().port);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment