When we use express in Node.js, we first use
const express = require('express')
to import express module, and this will return a function.
Then we use
const app = express()
Here’s my question:
-
What does this
express()
return?Because we can use methods like
app.get()
orapp.delete()
. I thought thatexpress()
probably returns an object -
If
express()
returns an object, why didn’t express just export a object when weconst express = require('express')
at the beginning than export a function?
1
This is what it gets exported: express.js on GitHub
It exports a so-called factory function: a function that each time it gets called it creates you a new app
(express application). This allows you to create more than one (isolated) application instance.
The factory function itself returns you another function
that has its own methods and properties (as legal according to js).
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;
}