const http = require('http');
const path = require('path');
const globalFooter = `
`;
function buildPage(title, bodyContent) {
return `
${title}
${bodyContent}
${globalFooter}
`;
}
const server = http.createServer((req, res) => {
if (req.url === '/favicon.ico') {
res.writeHead(204);
res.end();
return;
}
let htmlContent = '';
if (req.url === '/') {
htmlContent = buildPage('Index', 'Welcome to the home page.
About
');
} else if (req.url === '/about') {
htmlContent = buildPage('About Us', 'This is the about page.
Index
');
} else if (req.url == '/code.txt') {
const filePath = path.join(__dirname, 'code.txt');
res.set('Content-Type', 'text/plain');
res.set('Content-Disposition', 'inline');
res.sendFile(filePath, (err) => {
if (err) {
console.log(err);
res.status(500).send("Could not read file.");
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end(buildPage('404 Not Found', 'Page does not exist.
'));
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(htmlContent);
});
const PORT = 3005;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});