Skip to content

Instantly share code, notes, and snippets.

@umstek
Last active July 23, 2016 06:31
Show Gist options
  • Save umstek/54343f07b41a72e454434898720b56b8 to your computer and use it in GitHub Desktop.
Save umstek/54343f07b41a72e454434898720b56b8 to your computer and use it in GitHub Desktop.
Simple NodeJS server, serving static files.
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