Why use express() instead of just using require("express") on JavaScript? [duplicate]
Solution 1:
The export
of the express
package is a function named createApplication
(see here). Calling this function produces an object. I believe it is done this way so that the mixin
s are produced appropriately at run-time.
Also, keep in mind that in JavaScript, there are no types. Nothing is strictly an object. This function, for instance, has function members.
exports = module.exports = createApplication;
exports.query = require('./middleware/query'); // Assigning a member function to the `createApplication` function.
Because of this, you can call express()
, but also call express.query('whatever')
. JavaScript is pretty nonsense if you try to interpret it as a well-defined object-oriented language.
Solution 2:
Your question makes an incorrect assumption, you say
why don't we call function of the
express
object
but require("express")
returns a Function
.
It's a difference in what is exported. One exports an Object with properties attached to it while the other exports a Function.
Express does the latter. See express source:
exports = module.exports = createApplication;
function createApplication() {...};
While node does the former, node fs source:
module.exports = fs = {...};