Skip to content

Instantly share code, notes, and snippets.

@jamesgeorge007
Last active March 8, 2018 13:24
Show Gist options
  • Save jamesgeorge007/f9fbdc175b12a4b2aed42a5cbce46c7c to your computer and use it in GitHub Desktop.
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.
<!DOCTYPE html>
<html>
<head>
<title> Index Page </title>
</head>
<body>
<p> This is the index page. </p>
</body>
</html>
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();
}
}
}
var http = require('http');
var route = require('./route.js')
http.createServer(route.extract_url).listen(8080);
console.log('Listening on port 8080.')
<!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