Skip to content

Instantly share code, notes, and snippets.

@foysalit
Created March 23, 2017 20:15
Show Gist options
  • Save foysalit/e9b2e97e0d207be942938a78c95fdbf6 to your computer and use it in GitHub Desktop.
Save foysalit/e9b2e97e0d207be942938a78c95fdbf6 to your computer and use it in GitHub Desktop.
var http = require('http');
var fs = require('fs');
//server creation
var server = http.createServer(function(req,res){
console.log("request was made: " + req.url);
//creating routing system for the server
var routeToFile = {
'/': '/index.html',
'/home': '/index.html',
'/contact': '/contact.html',
'/404': '404.html'
};
if(routeToFile[req.url]){
res.writeHead(200,{'Content-Type':'text/html'});
fs.createReadStream(__dirname + routeToFile[req.url]).pipe(res);
}else if(req.url === '/api/ninjas'){
var ninjas = [{name:'rushdi',age:22},{name :'kader',age:34}];
res.writeHead(200,{'Content-Type':'application/json'});
res.end(JSON.stringify(ninjas));
}else{
res.writeHead(404,{'Content-Type':'text/html'});
fs.createReadStream(__dirname + routeToFile['/404']).pipe(res);
}
});
//response call
server.listen(3000,'127.0.0.1');
console.log("hi the result is shown and it is listening in port 3000");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment