DEV Community

Cover image for Nodejs class-based server
Alexs Ruiz
Alexs Ruiz

Posted on

Nodejs class-based server

do you have noted that when you are building a nodejs server (express) and this one starts to grow, the main file (generally index.js) has a bunch of imports, functions, and configurations that make the code not legible or tidy?

we can take a look at this example:

Image description

a good way to solve this can be to create a server based on classes which will allow us to have a more readable code and will give us the benefit of reusing this server for future projects since it provides us with a structure that will be more readable

taking this into account we will modify our server

we'll create a new file called "server.js" and then to create a class:

Image description

let's configure express into our class (also the port)

Image description

Now, let's remember that everything that is inside the constructor method of our class, will be executed when an instance of the class is created. This is important because we can take advantage of this behavior to create certain methods which are executed once the server instance is created

Image description

We see how in a descriptive way the method encapsulates the logic of what the code inside will do

methods:

  • routes
  • getConnection
  • middleware

We are going to execute them when instantiating the class, but the method listen is the one that will allow us to decide from when our server can start listening. Let's see it. First let's make these methods run inside the constructor method:

Image description

now, let's modify our listen method

Image description

We see that the configuration is practically the same since we continue using express, but now making use of "this"

In this way then we can create our server in a more orderly way separating our server in code blocks

Let's create now an instance of our server and let's see another important detail. Inside our file "index.js" we are going to require our server class and we are going to create an instance of the class which we will call app, then with app we can execute the listen method and indicate to our server that it can start listening through the port that we have defined

Image description

Now, if we look at our "server.js" file we have made use of "process.env" to require the port because in order to access the environment variables with our server implementation we are going to configure here in the "index.js" file the corresponding module for it

Image description

We now have a server that provides us with a clearer and easier to follow structure when structuring our server.

I hope this example has been helpful :)

Node Server Gist

Top comments (0)