https://nodejs.org/api/modules.html#requireid
require(id)# Added in: v0.1.13 id module name or path
Returns: exported module content
What does "module content" mean?
const x = require('express');
const y = x();
What is getting stored in x()?
Why do we need to access x as a function and store it in y?
CodePudding user response:
A module is a bundle of related code.
Express is a module.
Modules can export values (much like object properties have values).
The exported values can be any type of value.
Functions are a type of value.
The value exported by Express is a function.
You can tell because the documentation tells you to call it as a function and also by looking at the source code.
CodePudding user response:
require(id)
is the CommonJS syntax for importing modules whether that's via their npm package name or a path to a js/json file. When the function is called with a package name like "express"
. That package is looked up in the node_modules
directory and it tries to find an entrypoint in the node_modules/express/package.json
file or if a main
file isn't specified (as in the case of express) node_modules/express/index.js
can be used.
Following the imports from index.js
lead you yo lib/express.js
where the main exported function can be found:
/**
* Expose `createApplication()`.
*/
exports = module.exports = createApplication;
/**
* Create an express application.
*
* @return {Function}
* @api public
*/
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
// expose the prototype that will get set on requests
app.request = Object.create(req, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
// expose the prototype that will get set on responses
app.response = Object.create(res, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
app.init();
return app;
}
as you can see in the code snippet above x
is express' createApplication
function since it's assigned to the export
variable. As to why you need to call the x
function, that's simply express' chosen way to instantiate their application, other packages do it differently.
CodePudding user response:
Say you have those files:
function.js
:
const foo = () => console.log("Hello Word");
module.exports = foo;
index.js
:
const x = require('./function');
// x == foo
x(); // will log Hello Word
That's what's happening with express
. Express
exports a function in express.js
, and in order to use it, you should call that function.
And if you hadn't had that module.exports = foo
in function.js
, x
would be equal to {}
.