Why we don't directly do "app = require('express')"?

Issue

Almost in all NodeJS application codes I see the following lines:

express = require('express');
app = express();

And the question comes to my mind: why we don’t directly do:

 app = require('express');

Solution

If you mean

app = require('express')();

Then it’s bad practice of integrating/using express.
Assume we are going to use express to create a simple api server with routing. so, basically the boilerplate would be –

const express = require('express');
const app = express();

app.use(express.json());

app.get('/', (req, res) => {
   res.json({
      type: 'success',
      message: 'We can send json response because we used json module from express :D'
   });
});

app.listen(8000)

So, here we used json module to parse the response as json data and we did that using built in module of express.

If we haven’t declared express globally then we have to call the express function again to use the json module.

For example if we don’t declare express globally and want to use router and urlencoded parser module then the code would be like this

const app = require('express')();
const json = require('express').json;
const urlencoded = require('express').urlencoded;

app.use(json());
app.use(urlencoded({extended: true}));

And I think it’s not good practice of writing proper code. You have to call and create new variables for every modules you want to use from the express.

Hope you get it! I tried my best to make it clear for you from my knowledge.

Answered By – Your Chocomate

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.