Reputation: 1654
Saw this style of import on Github and was wondering why it is used? What's the deal with the () in the end?
const logger = require('pino')()
vs
const logger = require('pino');
Upvotes: 0
Views: 429
Reputation: 56467
const logger = require('pino')();
is equivalent to
const loggerFn = require('pino');
const logger = loggerFn();
Does this help?
Let me give a more concrete example. Consider
foo.js
module.exports = function() {
return 1;
};
and now in some other module
const fooFn = require('foo');
// fooFn is our defined function
const foo = fooFn();
// foo is 1
versus
const foo = require('foo')();
// foo is 1
which is equivalent.
So basically with pino
package when you require('pino')
you get a function which you then have to call. That's how the package was designed.
Upvotes: 2
Reputation: 406
To answer your question, you just need to understand what require
does. When require
is called, NodeJS returns the value of module.exports
in the module you are requesting. In the case of pino, module.exports
is equal to a function, so when you add the parenthesis to the end of the require
statement, you are simply calling the function returned by require
.
Upvotes: 1