If I do the following:
// at the end of database.js
module.exports = mongoConnect;
module.exports = getDb;
// app.js
const mongoConnect = require('./util/database').mongoConnect;
mongoConnect();
I get the error: ERROR: mongoConnect is not a function
.
But if I instead export them like this:
// at the end of database.js
module.exports = {
mongoConnect,
getDb,
};
Then running console.log(mongoConnect)
in app.js
gives the following:
{
mongoConnect: [Function: mongoConnect],
getDb: [Function: getDb],
}
and app.js
can use mongoConnect
just fine.
Why can't I use the first format?
You are overwriting the exports, thus only the last value is saved. Besides, when directly assigning exports
, then require('...')
will be that exact exports.
Your second example is how you're meant to export multiple values:
// module
module.exports = {
mongoConnect,
getDb,
};
// other module
const module = require('./module');
module.getDb(...);
// or alternatively
const { getDb } = require('./module');
getDb(...);