Skip to content

Instantly share code, notes, and snippets.

Created January 5, 2012 08:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/1564270 to your computer and use it in GitHub Desktop.
Save anonymous/1564270 to your computer and use it in GitHub Desktop.
var http = require('http');
var fs = require('fs');
var ip = '127.0.0.1';
var port = 2000;
var www = process.cwd();
var mimetypes = {'html': 'text/html', 'js': 'text/javascript', 'css': 'text/css', 'png': 'image/png', 'svg': 'image/svg'};
http.createServer(function (req, res) {
fs.realpath(www+req.url, function(err, realpath){
if (err || realpath.substr(0, www.length+1) != www+'/')
{
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('No such file exists, sorry!');
}
else
{
var filename = realpath.split('/').pop();
var extension = (filename.split('.').length > 1)
? filename.split('.').pop()
: 'txt';
var mimetype = (mimetypes[extension] === undefined)
? 'application/octet-stream'
: mimetypes[extension];
res.writeHead(200, {'Content-Type': mimetype});
fs.createReadStream(realpath).pipe(res); //herein lies the problem
res.end();
}
});
}).listen(port, ip);
console.log('Serving '+www+' at '+ip+':'+port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment