Last active
July 7, 2016 02:18
-
-
Save image72/d85e716e12594a111bcc895a4bd8899f to your computer and use it in GitHub Desktop.
Node server without framework. via https://developer.mozilla.org/en-US/docs/Node_server_without_framework
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 fs = require('fs'); | |
| var path = require('path'); | |
| http.createServer(function (request, response) { | |
| console.log('request ', request.url); | |
| var filePath = '.' + request.url; | |
| if (filePath == './') | |
| filePath = './index.html'; | |
| var extname = String(path.extname(filePath)).toLowerCase(); | |
| var contentType = 'text/html'; | |
| var mimeTypes = { | |
| '.html': 'text/html', | |
| '.js': 'text/javascript', | |
| '.css': 'text/css', | |
| '.json': 'application/json', | |
| '.png': 'image/png', | |
| '.jpg': 'image/jpg', | |
| '.gif': 'image/gif', | |
| '.wav': 'audio/wav', | |
| '.mp4': 'video/mp4', | |
| '.woff': 'application/font-woff', | |
| '.ttf': 'applilcation/font-ttf', | |
| '.eot': 'application/vnd.ms-fontobject', | |
| '.otf': 'application/font-otf', | |
| '.svg': 'application/image/svg+xml' | |
| }; | |
| contentType = mimeTypes[extname] || 'application/octet-stream'; | |
| fs.readFile(filePath, function(error, content) { | |
| if (error) { | |
| if(error.code == 'ENOENT'){ | |
| fs.readFile('./404.html', function(error, content) { | |
| response.writeHead(200, { 'Content-Type': contentType }); | |
| response.end(content, 'utf-8'); | |
| }); | |
| } | |
| else { | |
| response.writeHead(500); | |
| response.end('Sorry, check with the site admin for error: '+error.code+' ..\n'); | |
| response.end(); | |
| } | |
| } | |
| else { | |
| response.writeHead(200, { 'Content-Type': contentType }); | |
| response.end(content, 'utf-8'); | |
| } | |
| }); | |
| }).listen(8125); | |
| console.log('Server running at http://127.0.0.1:8125/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment