Last active
May 27, 2017 12:02
-
-
Save Talha-T/a50209602b16f568368f6d7e1534c284 to your computer and use it in GitHub Desktop.
Node.js Server That Includes Other Files Too
This file contains 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 url = require("url"); | |
var fs = require("fs"); | |
var Path = require("path"); | |
function renderHtml(path, response) { | |
fs.readFile(path, | |
null, | |
function(error, data) { | |
if (error) { | |
response.writeHead(500, { "Content-Type": "text/plain" }); | |
response.writeHead(404); | |
response.write("Page not found or route not defined."); | |
} else { | |
response.writeHead(200, { "Content-Type": "text/html" }); | |
response.write(data); | |
} | |
response.end(); | |
}); | |
} | |
module.exports = { | |
handleRequest: function(request, response) { | |
var path = url.parse(request.url).pathname; | |
var ext = Path.extname(path); | |
var contentType; | |
switch(ext) { | |
case ".html": | |
contentType = "text/html"; | |
break; | |
case ".sass": | |
case ".scss": | |
case ".css": | |
contentType = "text/css"; | |
break; | |
case ".js": | |
contentType = "text/javascript"; | |
break; | |
case ".png": | |
contentType = "image/png"; | |
break; | |
case ".jpg": | |
case ".jpeg": | |
contentType = "image/jpeg"; | |
break; | |
case ".ico": | |
contentType = "image/x-icon"; | |
break; | |
} | |
response.writeHead(200, { 'Content-Type': contentType }); | |
switch (path) { | |
case "/": | |
renderHtml("./index.html", response); | |
break; | |
default: | |
console.log("Path: " + path); | |
fs.readFile("." + path, | |
null, | |
function(error, data) { | |
if (error) { | |
response.writeHead(500, { "Content-Type": "text/plain" }); | |
response.writeHead(404); | |
console.log(error.message); | |
response.write("Page not found or route not defined."); | |
} else { | |
response.writeHead(200, { "Content-Type": contentType }); | |
response.write(data); | |
} | |
response.end(); | |
}); | |
//response.end(); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment