Project Creation - Best Practice

In order to create a best practice project creation for native Node.js projects, let us discuss a todo list for that.

Example 16.3. Your Second Server Refined, myg52/main.js

The following code is similar to listing 5.1 from your textbook augmented with listings 5.2 and 5.3.

"use strict";

const http = require("http");
const httpStatus = require("http-status-codes");
const hostname = "127.0.0.1";
const port = 3000;
const app = http.createServer();            // server as an obj

const getJSONString = function (obj) {      // prettyprint obj
    return JSON.stringify(obj, null, 4);
}

app.on("request", function (req, res) {     // eventhandler for "request"
    console.log("Log: Received an incoming request!");
    console.log("Log: Method: " + req.method);
    console.log("Log: URL: " + getJSONString(req.url));
    console.log("Log: Headers:\n" + getJSONString(req.headers));
                                            // prep response header
    res.writeHead(httpStatus.OK, {
        "Content-Type": "text/html; charset=utf-8"
    });
                                            // prep response body
    let responseMsg = "<h1>Kilroy was here!</h1>";
    responseMsg += "<p><kbd>myg52</kbd> at your disposal</p>";
    res.write(responseMsg);                 // respond
    res.end();                              // sends response http
});

app.listen(port, hostname, function () {
    console.log(`Server running, and listening at http://${hostname}:${port}/`);
});

On your CLI do npm test. Then go to your browser and do http://localhost:3000. Check the server's log.