Created
October 1, 2015 16:06
-
-
Save emilyhorsman/8b260fad9931476380f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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