Skip to content

Instantly share code, notes, and snippets.

@emilyhorsman
Created October 1, 2015 16:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emilyhorsman/8b260fad9931476380f2 to your computer and use it in GitHub Desktop.
Save emilyhorsman/8b260fad9931476380f2 to your computer and use it in GitHub Desktop.
var path = require('path');
var http = require('http');
var fs = require('fs');
var spawn = require('child_process').spawn;
function safe_path(request_url) {
var cwd = path.resolve(path.dirname());
var target = path.resolve(request_url.slice(1));
if (target.indexOf(cwd) !== 0)
return;
return target;
}
http.createServer(function(req, res) {
var image_path = safe_path(req.url);
if (!image_path) {
res.writeHead(500);
return res.end();
}
if (!fs.existsSync(image_path) || req.url == '/') {
res.writeHead(404);
return res.end();
}
var webp = spawn('cwebp', [image_path, '-o', '-']);
webp.stderr.on('data', function(data) {
console.log(data.toString('utf8'));
});
webp.stdout.pipe(res);
res.writeHead(200, {
'Content-Type': 'image/webp',
});
}).listen(4000, '127.0.0.1');
console.log('http://127.0.0.1:4000');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment