Reputation: 1213
Let's say I have an application as following:
server.js
(main) is requiring different external node packages, like underscore.js
.
var Underscore = require("underscore");
server.js
is also requiring some modules defined in my application it-self; For example it could requires a Router module, to handle Express
routes.
var Router = require("./sources/router.js");
I have then my router.js
file as following :
var Router;
Router = (function() {
function Router(app, oauth) {
app.get('/', function(request, response) {
// ...
});
}
return Router;
})();
module.exports = Router;
Questions:
If I want to use underscore
inside my Router
module, should I re-require again ? Should I do that for every modules ? What is the impact?
I would end up with something like:
var Router;
Router = (function() {
Router.prototype.underscore = require("underscore");
function Router(app, oauth) {
app.get('/', function(request, response) {
// this.underscore. ...
// using underscore ...
});
}
return Router;
})();
module.exports = Router;
and
var Underscore = require("underscore");
var Router = require("./sources/router.js");
router = new Router();
I could obviously also inject as a parameter it when initializing Router
, but this doesn't look to me like a viable option in an application where I may end up using dozens of packages, especially for very general purpose package like this one.
var underscore = require("underscore");
var Router = require("./sources/router.js");
var router = new Router(underscore);
Alternatively I could set the underscore
var as a global one, but I don't really like this option.
Is there any other options ?
What is the impact of systematically importing packages in every modules - in term of execution time, memory ? I would like to understand the behavior of the node engine in such cases.
Upvotes: 1
Views: 41
Reputation: 17505
Yes, you should just require
it again. Node caches required modules, so the second time you require
something it doesn't actually run that file; it just returns the cached object. So the memory impact is basically 0 (an extra pointer to the same object, more or less) and the execution time is similarly negligible (the cost of a lookup in an object by the module name).
This means that the objects returned by the two require
s aren't just identical; they're literally the same object. Any change to one will affect the other. Because of this, you can extend the module in one place and get those extensions everywhere.
Upvotes: 2