When does the javascript function need empty parenthesis after require statement?

Viewed 77

I am using module.exports for exporting functions. Most of them are imported like this:

const logger = require('../middleware/logger')

I understand that if I needed to pass an argument to the function I would use:

const logger = require('../middleware/logger')(arg)

But recently I ran into a function I need to call with empy parenthesis:

require('./startup/db')()

Otherwise The connection to database is not established. There is code from './startup/db' :

const mongoose = require('mongoose')
mongoose.set('useCreateIndex', true)
const logger = require('../middleware/logger')

module.exports = function () {
   mongoose.connect('mongodb://localhost:27017/data', {
         useNewUrlParser: true,
         useUnifiedTopology: true,
      })
      .then(() => logger.info('Connected to MongoDB'))
}

Could anyone explain when require('module') is not working and I should use require('module')() instead?

1 Answers

This is because './startup/db' returns a function instead of a value. This function needs to be called else just a reference to the function is stored.
Now since this function does not require a parameter and just needs to be invoked, no values are passed to it.

Related