简体   繁体   中英

ExpressJS require

I was reading over the Express.JS 4.x API and was curious about how they set this up. Here's my understanding of what is happening: In this sample code in the Express.JS 4.x API, the express module is imported and assigned to a variable express. That variable is then used to call the express constructor and is assigned to the variable app.

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(3000);

Is there a difference if the express module is directly assigned to app or is the assignment above just for readability? As follows:

var app = require('express')();

A node module can return a constructor that is both a constructor AND also has properties (since functions are objects that can have properties).

Your first method allows you to access any other properties or methods that the constructor might have. The second method does not permit that since it doesn't retain a reference to the constructor.

In the ExpressJS documentation, I do see some items that are referenced via the express object such as:

var express = require('express');
var app = express();
var router = express.Router();
router.get('/', function (req, res, next) {
    next();
});
app.use(router);

and

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));

If you don't need to retain a reference to the constructor in order to access these other methods on it, then there is no difference between your two options as they execute the same code. Your second one just doesn't retain a reference to an intermediate step that can be used later to access other things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM