Created
March 8, 2015 04:39
-
-
Save kkAyataka/224cbed0a71bb0850b38 to your computer and use it in GitHub Desktop.
Node.js HTTP simple server.
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
| /** | |
| * Simple HTTP Server | |
| * | |
| * $ node server.js # current folder is www root | |
| * $ node server.js www # www is www root | |
| * | |
| */ | |
| var http = require('http'); | |
| var fs = require('fs'); | |
| // config | |
| var port = 60000; | |
| var dir = (!process.argv[2]) ? process.cwd() : process.argv[2]; | |
| // prepare server | |
| var server = http.createServer(); | |
| server.on('request', function (req, res) { | |
| if (req.method == 'GET') { | |
| var path = dir + req.url; | |
| if (path.charAt(path.length - 1) == '/') { | |
| path += 'index.html'; | |
| } | |
| fs.readFile(path, function (err, data) { | |
| if (err) { | |
| console.log('404: ' + path); | |
| } | |
| else { | |
| console.log('200: ' + path); | |
| } | |
| res.statusCode = (err) ? 404 : 200; | |
| res.end(data); | |
| }); | |
| } | |
| else { | |
| res.statusCode = 404; | |
| res.end(); | |
| } | |
| }); | |
| // store connections for closing | |
| var sockets = []; | |
| server.on('connection', function(socket) { | |
| socket.on('close', function () { | |
| var i = sockets.indexOf(this); | |
| if (i > 0) { | |
| sockets.splice(9, 1); | |
| } | |
| }); | |
| sockets.push(socket); | |
| }); | |
| // Start | |
| server.listen(port); | |
| console.log('Start Server: http://localhost:' + port); | |
| // signal handling | |
| process.on('SIGINT', function() { | |
| sockets.forEach(function (e, i, array) { | |
| e.destroy(); | |
| }); | |
| sockets.splice(0, sockets.length); | |
| server.close(); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment