Code Explanation
View the Siteconst http = require('http');
const {readFileSync} = require('fs');
// Get files
const indexpg = readFileSync('./indexbanner/index.html');
const aboutpg = readFileSync('./indexbanner/about.html');
const mainsty = readFileSync('./indexbanner/main.css');
const banimg = readFileSync('./indexbanner/banner_forest.png');
The first two lines store the http and file system modules inside variables.
The rest of the lines reads each file and stores them in a variable.
const server = http.createServer((req, res)=> {
const url = req.url;
if(url === '/'){
res.writeHead(200,{'content-type':'text/html'});
res.write(indexpg);
res.end();
} else if(url === '/main.css') {
res.writeHead(200,{'content-type':'text/css'});
res.write(mainsty);
res.end();
} else if(url === '/banner_forest.png') {
res.writeHead(200,{'content-type':'image/x-png'});
res.write(banimg);
res.end();
} else if(url === '/about'){
res.writeHead(200,{'content-type':'text/html'});
res.write(aboutpg);
res.end();
} else {
res.writeHead(404,{'content-type':'text/html'});
res.write('404 Page Not Found
');
res.end();
}
});
server.listen(8080);
console.log('Server reached at http://localhost:8080/');
Here's the main server logic. We used the http module to create a server and used the url to pass if else statements. Depending
on the URL condition, different HTML pages get sent.