Create a simple web server using Node.js using HTTP module

Create a web server using Node.js

Web server creation has never been this easy with Node.js HTTP module. The HTTP module allow us to create a web server listening on some port and returning a response to the client in a few lines of code using the createServer method which create the server and the listen that bind it to our chosen port. In order to start the server all you have to do is run the "node server.js" command (server.js is your file name).

1 Node.js Web Server - The simple version

const http = require("http");

const port = process.env.PORT || "3100";

const server = http.createServer(function (req, res) {
  //set content type
  res.writeHead(200, {"Content-Type": "text/html"});
  //write a response to the client
  res.write(`<p>Hello World! from ${req.url} using the ${req.method} method</p>`);
  //end the response
  res.end();
}).listen(port);

The ` is called Template Literals, you can find an example in the previous link.

2 Node.js Web Server - The detailed version

const http = require("http");

const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof addr === "string" ? "pipe " + addr : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};

const onListening = () => {
  const addr = server.address();
  const bind = typeof addr === "string" ? "pipe " + addr : "port " + port;
  console.log("Listening on " + bind);
};

const port = normalizePort(process.env.PORT || "3100");

const server = http.createServer(function (req, res) {
  //set content type
  res.writeHead(200, {"Content-Type": "text/html"});
  //write a response to the client
  res.write(`<p>Hello World! from ${req.url} using the ${req.method} method</p>`);
  //end the response
  res.end();
});
server.on("error", onError);
server.on("listening", onListening);
server.listen(port);