Express Js, How to beautify and Readable

Faraz Faraji
Nerd For Tech
Published in
4 min readMar 30, 2021

What is the Story

I started NodeJs developing 4 years ago. At first, I was working on some urgent projects and I was forced to finish them As soon as possible, and I didn’t have enough time to create any good structure for my Projects.

After a while, I stuck in my Spaghetti Code and I learned if I have 10 minutes to cut all trees, Sharpen my ax for 9 minutes, and 1 minute to cut all trees. And now I want to share my experience of avoiding Spaghetti code and share my code structure.

First Step — Decide about frameworks.

Don’t forget to use a framework, Select it correctly. if you are going to create a big application for handling endpoints, I recommend using Typescript something like NestJS (Don’t forget, if it’s a big Application), or If you want to process something or your application not too big use something like ExpressJS. Most of my projects are MVP so, here we will continue on ExpressJs.

Install Express.

I saw many times, developers install ExpressJs and they start writing server code directly. But I strongly recommend you, use Express CLI. Then you can start your code in just 5 seconds.

mkdir test-project
cd test-project
express

If you open your code, you will see something like this. It’s a basic structure of ExpressJs framework. but I want to change it to my style. Like me, if you don’t want to have any UI, so remove the public and views folder to clean your structure.

Let’s take a look at the project skeleton. in bin folder there is one file called www. it’s a file that included all codes to run the server. I think you don’t need to change anything in this file now. routes folder is included all routes configs. there are two default index.js and users.js and your main Code is into the app.js

Increase Technical Capability

At first, I prefer to create some folders, services, assets, models,tests and helpers.

  • Assets is included assets files like keys, config files and etc.
  • helpers is included utils files like log management or middlewares
  • models is included database models files
  • services is included business layer to connect your routes to your logic and models
  • tests is included all tests files

Also, I have one file in every one of my projects, I called di.js for managing my databases. Finally, you will have something like this:

My Project Skeleton

Naming Files

to finds your files easily I always set their name, according to their folder name. For example, if I want to define a new service for calculation, I name it calculation.service.js Or for routes I use users.route.js. So I rename all routes files at the first in the project, index.js to index.route.js and users.js to users.route.js. Also i should change routes name in the app.js too

var indexRouter = require('./routes/index.route');
var usersRouter = require('./routes/users.route');

Also if you want to know more about skeleton in Express js, i recommend you, watch this video

What is DI.js File

imagine you are using Redis, Postgres, and some other databases in one project. So we can not define Redis connection in each service file. To solve this problem I decide to create my own DI, (Dependency Injections ).

const Sequelize = require('sequelize');
const Redis = require("async-redis");
class di{
config = {};
constructor(_config){
this.config = _config;
this.postgres = null;
this.redis = null;
}
async connectToPostgres(){
const config = this.config;
this.postgres = new Sequelize(`postgres://${config.postgres.username}:${config.postgres.password}@${config.postgres.host}:${config.postgres.port}/${config.postgres.db_name}`, {logging: false});
try {
await this.postgres.authenticate();
console.log('Connection to postgres has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
async connectToRedis(){
const config = this.config;
this.redis = Redis.createClient(config.redis);
}
}
const setting = require("./assets/setting");
const DI = new di(setting.test.database);
module.exports = DI;

and for initializing DI, we should load this class in app.js

const di = require("./di");
di.connectToPostgres();
di.connectToRedis();

In the next lesson, I will explain How to Implement a Logging System.
Don’t forget to ask your questions and please feel free to write your comment here.

Follow Me in Youtube and Instagram to get updates

Youtube Channel
Instagram

--

--

Faraz Faraji
Nerd For Tech

Life is doing things what you love. Sharing my Idea and ready to listen to everyone.