How does app.listen() create a server connection from receiving a PORT number?


#1

Question

How does app.listen() create a server connection from receiving a PORT number?

Answer

express is a magnificent library that abstracts a lot of different processes that we would have to implement with Node otherwise, it makes it easier for us, but it could also keep us in the dark.

The listen() method of express’ application object implements the http and https node modules, this two already have abstracted a lot by having a createServer() method but what it really can do is build a server object which is sent like a manifest or a passport handed to the customs official to show that it has the documentation necessary to be there, and it can also set a pipe which is simply an open connection that allows passing data multiple times.

If we were to have to use only Node setting up an http server might look like so:

const http = require('http'); /* <--- the module */

http.createServer((request, response) => { // createServer method receives a callback 
                                          // with two values
  request.on('error', (err) => {  // request is an object passed and created by createServer
    console.error(err);            //error catching
    response.statusCode = 400;
    response.end();
  });
  response.on('error', (err) => {
    console.error(err);
  });
  if (request.method === 'POST' && request.url === '/echo') { // simple post request capability
    request.pipe(response); //pipe method  here is where it opens the connection for the response
  } else {
    response.statusCode = 404;
    response.end();
  }
}).listen(8080); //and this is node's listen method that simply turns the port number into part of the server's path

express’ app.listen() method takes care of this and more; keeping an open connection on the desired passed PORT. Since it is a listen method of app, app is already manipulating requests not inside of createServer but with its handler methods, for example instead of having:

  if (request.method === 'POST' && request.url === '/echo') { ...

we can simply write:

app.post('/echo', (req, res)=>{...});

app.listen uses the http and https node modules to create the server and aided by the get, put, post, create, & delete methods it handles the type of requests translating them for node.

In both cases, the PORT number is simply used to append to the server’s location as an address, that way we could have as many local servers running as our computer can handle while every single one has their own port where requests related to the specific server can arrive to.


FAQ: Code Challenges - Code Challenge