Last active
October 25, 2022 04:38
-
-
Save Deeks900/cd0c7bdd30c746dc8b25ac365b9e86e5 to your computer and use it in GitHub Desktop.
Node Server
This file contains hidden or 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
//Taking out http module from node | |
const http = require('htttp') | |
const fs = require('fs') | |
//Making the server | |
const server = http.createServer((req, res)=>{ | |
//we can send response from our server like this | |
res.setHeader('Content-Type', 'text/html'); | |
res.write(<h1>Wohoo! Server is running</h1>); | |
res.end(); | |
//Another way to send response is that write html in a separarte file and then send this file | |
let path = './' | |
switch(req.url){ | |
case '/': | |
path += 'index.html'; | |
res.statusCode = 200; | |
break; | |
case '/about': | |
path += 'about.html'; | |
res.statusCode = 200; | |
break; | |
case '/about-me': | |
res.statusCode = 301; | |
res.setHeader('Location', '/about'); | |
res.end(); | |
default: | |
path += '404.html' | |
res.statusCode = 404; | |
break; | |
} | |
fs.readFile(path, (err, fileData)=>{ | |
if(err) | |
console.log(err); | |
else | |
res.end(fileData); | |
}) | |
}) | |
//Now make server listen to the requests | |
server.listen(3000, 'localhost', ()=>{ | |
console.log("server is listening on port 3000") | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment