In order to learn web server programming in Node and JavaScript, I decided to implement a simple web server that only does one thing:
- Display data of the HTTP request as an HTML table.
The actual data to display is arbitrary. In this example I'm displaying the contents of the header, along with the method, url, and http versions.
Here is the working solution:
const http = require('http');
const port = 3344;
const htmlCSS = `
<style>
body {
font-family: sans-serif;
}
td {
border: 1px solid black;
padding: 0.5rem;
}
table {
margin: 0 auto;
}
</style>
`;
const server = http.createServer((req, res) => {
const {
headers,
method,
url
} = req;
console.log(`\n${headers['user-agent']}\n${method}\n${url}`);
console.log(new Date());
console.log();
writeResponse(req, res);
});
server.listen(port);
function writeResponse(req, res) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
writeBody(req, res);
res.end();
}
function writeBody(req, res) {
const htmlTitle = '<title>Your Request Is</title>';
const htmlEncode = '<meta charset="UTF-8">';
const htmlHead = `<head>${htmlTitle}${htmlCSS}${htmlEncode}</head>`;
const htmlTop = `<html lang="en">${htmlHead}<body>`;
const htmlBot = '</body></html>';
res.write(htmlTop);
writeTable(req, res);
res.write(htmlBot);
}
function writeTable(req, res) {
const htmlTableTop = '<table><tbody>';
const htmlTableBot = '</tbody></table>';
res.write(htmlTableTop);
writeAllRows(req, res);
res.write(htmlTableBot);
}
function writeAllRows(req, res) {
const {
httpVersion,
httpVersionMinor,
httpVersionMajor,
headers,
method,
url
} = req;
for (const key in headers) {
writeRow(res, key, headers[key]);
}
writeRow(res, 'method', method);
writeRow(res, 'url', url);
writeRow(res, 'httpVersion', httpVersion);
writeRow(res, 'httpVersionMinor', httpVersionMinor);
writeRow(res, 'httpVersionMajor', httpVersionMajor);
}
function writeRow(res, key, val) {
const entry = `<tr><td>${key}</td><td>${val}</td></tr>`;
res.write(entry);
}
While I have some particular questions, I'm looking forward for all kinds of feedback! So if you see anything at all that can be improved, any comment is much appreciated!
- Can I use other modules to make this job easier?
- For a job this simple, is it worth to work with HTML and CSS as separate files?
- How are HTML and CSS normally handled inside JS files (edits, appends, etc)?
- How well am I handling the construction of HTML and CSS?
- Can this be done more concisely?
- What would you do differently to improve this in any way?