Is starting express like this "const app = require('express')()" considered bad practice?

Issue

So title says it all. Never seen anyone use this syntax.

const app = require('express')()

I like to keep the main js file lean and have everything in modules so all I have there is 15 lines including comments.

Google didn’t help and haven’t found an answer here.

Is it bad practice to invoke express as you require it?

Solution

In general, your code should be the simplest and clearest way of reliably meeting your requirements. Any code that follows those simple guidelines will not be considered a bad practice in pretty much anyone’s book.

There may be other influences on the desired coding style such as team style guidelines, coding style already present in the file/module/project and certain things you may want to do for testing, debugging or reuse. But, since you don’t mention any of those influences, I will assume they are not present here.

So, with that first paragraph in mind, as long as you don’t need access to the express module elsewhere in this module, then doing:

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

is indeed the simplest and clearest way of accomplishing your goal and should not be considered a bad practice – in fact it should be considered a good practice.


On the other hand, if you were doing this:

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

....


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


....

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


....

app.use(require('express').static('public'));

Then, you’d have simpler and less redundant code (and perhaps a little faster since there are fewer function calls) if you loaded the express module into its own variable which you could then use everywhere else in that module:

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

....


const mainRouter = express.Router();


....

const subRouter = express.Router();


....

app.use(express.static('public'));

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published