0

To create a simple Web server with NodeJS and Express, all the tutorials giving examples like this

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

app.listen(3000, () => console.log("Started"))

app.get('/', (req, res) =>{
    res.send("Yaaa")
})

My question is, Why not write it like this?

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

app.listen(3000, () => console.log("Started"))

app.get('/', (req, res) =>{
    res.send("Yaaa")
})

The only difference is merging lines 1 and 2, as far as I'm not going to use/need the "express" constant anymore.

Is that wrong? And why?

MRashad
  • 165
  • 1
  • 1
  • 9
  • 1
    In the first way you also have access to the variable `express` which may expose more API stuff you might want? – evolutionxbox Jan 26 '22 at 10:48
  • 2
    Perhaps they use the first approach because it's easier to comprehend. People have trouble grasping [functions that return other functions](https://stackoverflow.com/q/18234491). – VLAZ Jan 26 '22 at 10:48

2 Answers2

2

As far as I know about express framework. Express exposes us to a lot of useful functions. If we don't require or import express in our application then, Our application will not be able to use those functions.
For example if you are creating some REST APIs then, We need our APIs to take form-data or raw as input. If we want to allow our application to take raw-json as input then, we need to add a middleware which consumes a built-in express function.

app.use(express.json())

If you want create an application that has a seperate folder for all the routes. Then, we use express.Routes() for that. That's how we create routes file in seperate routes folder:

import express from 'express';
import userController from 'path/to/user/controller';

const router = express.Router();

router.post('/follow/:userid/:following', helper.verifyToken, userController.follow);

router.get('/someRoute', userController.someAction);

export default router;

Similarly, If we want to serve some static HTML or some react-build. Then, we use express.static() inside app.use() middleware like this:

app.use(express.static('/path/to/static/folder'));
0

As long as you don't need access to the express module elsewhere in this file, then doing:

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

is the best way.

But if we require to use to this express module again and again. Such as below

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

const friendsRouter = require('express').Router();

Then it becomes a problem and you have require it again and again.

So to make our code less redundant, we use normal given approach. As in below code:

const express = require('express');
const app = express();
const friendRouter = express.Router();
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Shishir Naresh
  • 743
  • 4
  • 10