Last active
July 23, 2016 06:31
-
-
Save umstek/54343f07b41a72e454434898720b56b8 to your computer and use it in GitHub Desktop.
Simple NodeJS server, serving static files.
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 fs = require('fs'); | |
var http = require('http'); | |
http.createServer(function (request, response) { | |
var path = request.url; | |
console.log(request.method, request.url); | |
if (path === '/') { // Serving default page from code instead of a file. | |
var html = "<!DOCTYPE html>" + | |
"<html>\n" + | |
" <head></head>\n" + | |
" <body>\n <div id='content'></div>\n <script src='js.js'></script>\n </body>\n" + | |
"</html>"; | |
response.writeHead(200, { 'Content-Type': 'text/html' }); | |
response.end(html); | |
} else { | |
var content = null; | |
try { | |
content = fs.readFileSync("." + path); // read file content synchronously | |
} catch (error) { // File not found, permission error etc. | |
console.log(path, "doesn't exist. "); | |
response.writeHead(404, { 'Content-Type': 'text/plain' }); | |
response.end("Content not found. "); | |
return; | |
} | |
var ext = path.split('.').pop(); // gets the extension. | |
// console.log(content); | |
var extToIMT = { // Simple lookup to convert extensions to Internet Media Type | |
'txt': 'text/plain', | |
'html': 'text/html', | |
'js': 'text/javascript', | |
'css': 'text/css' | |
}; | |
var imt = ""; | |
if (ext in extToIMT) { | |
imt = extToIMT[ext]; | |
} else { // Unknown type. | |
imt = 'application/octet-stream'; | |
} | |
response.writeHead(200, { 'Content-Type': imt }); | |
response.end(content); | |
} | |
}).listen('8000'); // Start server. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment