Last active
March 8, 2018 13:24
-
-
Save jamesgeorge007/f9fbdc175b12a4b2aed42a5cbce46c7c to your computer and use it in GitHub Desktop.
A simple demonstration of Node JS routing based on the url given which also points towards the need of having assistance provided by frameworks like Express which eases the task.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title> Index Page </title> | |
</head> | |
<body> | |
<p> This is the index page. </p> | |
</body> | |
</html> |
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'); | |
renderHTML = (file, response) => | |
{ | |
response.writeHead(200, {'Context-Type':'text/html'}); | |
fs.readFile(file, null, (error, data) => | |
{ | |
if(error) | |
{ | |
response.writeHead(404); | |
response.write("File not Found!"); | |
} | |
else | |
{ | |
response.write(data); | |
} | |
response.end(); | |
}); | |
} | |
module.exports = { | |
extract_url : function(request, response) | |
{ | |
var path = url.parse(request.url).pathname; | |
switch(path) | |
{ | |
case '/index': | |
renderHTML('index.html', response); | |
break; | |
case '/user': | |
renderHTML('user.html', response); | |
break; | |
default: | |
response.writeHead(404); | |
response.write("Route is not defined!"); | |
response.end(); | |
} | |
} | |
} |
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 http = require('http'); | |
var route = require('./route.js') | |
http.createServer(route.extract_url).listen(8080); | |
console.log('Listening on port 8080.') |
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title> Users page </title> | |
</head> | |
<body> | |
<h1> Welcome User! </h1> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment