简体   繁体   中英

express.Router() and requires in Express.js

I am trying to organize my project according to Express 4.x new express.Router() method.

As Express' documentation describes it,

A router object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions.

For the sake of better understanding, let's consider this project structure:

project/
  index.js
  routes/
    myRouter.js
    ...
  ...

And the files themselves:

index.js

const express = require('express');
const app = express(); 
const path = require('path');

const myModule = require('myModule');   

app.use('/myRouter', require('routes/myRouter'));

// some more code using myModule set of functions

routes/myRouter.js

const express = require('express');
const path = require('path');
const router = express.Router();

const myModule = require('myModule'); 

router.get('/', function(req, res){
        // some more code using myModule set of functions 
      });

module.exports = router;

As you can see, both files need to use myModule 's functions, so AFAIK both files need to require myModule .

How does Express handle this situation?

As I see it, Express directly imports myRouter 's code into index.js via module.exports . If so, is the engine somehow pre-compiling it? And then aren't myRouters' requires redundant?

If not, how does it affect performance? Should I avoid routers for my kind of task?

First thing would be that it is not being compiled, it's not es6. Second app.js imports the module and run that module for your route so imports in your myRouter.js is completely necessary. This article would certainly help you understand modules. One more thing is that it does decrease your application performance. Express is used on node.js and node.js imports are optimised with V8 engine. So don't worry about performance.

How does Express handle this situation?

Express doesn't, Node does. From the docs

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature....

So taking your application into consideration, myModule is already cached by the time the router loads it as app.js would be required first; any performance impact would be negligible.

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