Created
May 2, 2014 12:07
-
-
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
This file contains hidden or 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 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