Skip to content

Instantly share code, notes, and snippets.

@TerryMooreII
Created May 2, 2014 12:07
Show Gist options
  • Save TerryMooreII/a1ff5499b2a1b1219cd7 to your computer and use it in GitHub Desktop.
Save TerryMooreII/a1ff5499b2a1b1219cd7 to your computer and use it in GitHub Desktop.
Fully functional web server in 30 lines of code - Cardinal Solutions ALF blog post
var http = require('http');
var path = require('path');
var fs = require('fs');
var base = __dirname;
http.createServer (function(req, res){
pathname = base + req.url;
console.log(pathname);
path.exists(pathname, function(exists){
if(!exists){
res.writeHead(404);
res.write('404 Bad Request');
res.end();
}else{
res.setHeader('Content-type', 'text/html');
res.statusCode = 200;
var file = fs.createReadStream(pathname);
file.on('open', function(){
file.pipe(res);
});
file.on('error', function(err){
res.writeHead(404);
res.write('404 Bad Request');
res.end();
})
}
})
}).listen('8881');
console.log('Server started: Listening on port 8881');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment