Created
February 19, 2019 16:10
-
-
Save cmjaimet/58481a7ddb563969992cbba8a93ee01e to your computer and use it in GitHub Desktop.
Very simple Node 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
/** | |
* VERY simple web server in Node with limited/no error trapping | |
*/ | |
var http = require( 'http' ); | |
var fs = require( 'fs' ); | |
const PORT = 8080; | |
function handleRequest( req, res ){ | |
var url = '/index.html'; // default path | |
var typ = 'text/html' // default file type | |
var file_ = ''; // file to handle | |
if ( '/' !== req.url ) { | |
// get the file mime type | |
var url = req.url; | |
var suffix = req.url.split( '.' ).pop(); | |
switch ( suffix ) { | |
case 'html': | |
case 'css': | |
typ = 'text/' + suffix; | |
break; | |
case 'js': | |
case 'jsx': | |
typ = 'text/javascript'; | |
break; | |
case 'jpeg': | |
case 'gif': | |
case 'png': | |
typ = 'image/' + suffix; | |
break; | |
case 'jpg': | |
typ = 'image/jpeg'; | |
break; | |
case 'ico': | |
typ = 'image/x-icon'; | |
break; | |
default: | |
typ = ''; | |
break; | |
} | |
} | |
if ( '' !== typ ) { | |
// get the file contents and pipe to browser | |
file_ = fs.readFileSync( '.' + url ); | |
res.writeHead( 200, { 'Content-Type': typ } ); | |
} | |
res.end( file_ ); | |
} | |
// create server | |
var server = http.createServer( handleRequest ); | |
// start server | |
server.listen( PORT, function() { | |
console.log( "Server listening on: http://localhost:%s", PORT ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment