Created
August 14, 2017 09:50
-
-
Save arpo/c79be9c9a3419a8fe5e738aeb642e3f2 to your computer and use it in GitHub Desktop.
A basic server for node js
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'); | |
var port = 3000; | |
http.createServer(function (request, response) { | |
//console.log('request starting...'); | |
var filePath = '.' + request.url; | |
if (filePath == './') | |
filePath = './index.html'; | |
var extname = path.extname(filePath); | |
var contentType = 'text/html'; | |
switch (extname) { | |
case '.js': | |
contentType = 'text/javascript'; | |
break; | |
case '.css': | |
contentType = 'text/css'; | |
break; | |
case '.json': | |
contentType = 'application/json'; | |
break; | |
case '.png': | |
contentType = 'image/png'; | |
break; | |
case '.jpg': | |
contentType = 'image/jpg'; | |
break; | |
case '.wav': | |
contentType = 'audio/wav'; | |
break; | |
case '.svg': | |
contentType = 'image/svg+xml'; | |
break; | |
case '.ttf': | |
contentType = 'application/x-font-ttf'; | |
break; | |
case '.woff': | |
contentType = 'application/x-font-woff'; | |
break; | |
} | |
fs.readFile(filePath, function (error, content) { | |
if (error) { | |
if (error.code == 'ENOENT') { | |
response.writeHead(404); | |
response.end('Ooops! Can\'t find that page :('); | |
response.end(); | |
} 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(port); | |
console.log('Server running at \nhttp://127.0.0.1:' + port + '/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment