jtwalters jtwalters - 1 month ago 7
Node.js Question

Nodejs, is better have alot of same require or use a handle?

Image this esctructure:

- app.js
- core/
- service_1.js
- service_2.js
- service_3.js
- service_4.js
- service_5.js
- modules/
- module_1.js
- module_2.js
- module_3.js


The app.js uses the 3 modules, so the code of the app is:

var m1 = require('./modules/module_1');
var m2 = require('./modules/module_2');
var m3 = require('./modules/module_3');

m1.exec();
m2.exec();
m3.exec();


And each model uses all the services, so they need:

var s1 = require('./../core/service_1');
var s2 = require('./../core/service_2');
var s3 = require('./../core/service_3');
var s4 = require('./../core/service_3');
var s5 = require('./../core/service_3');

// some stuff...


So, i need to know if this is the best way to handle that or maybe do a "serviceManager" like:

app.js

var m1 = require('./modules/module_1');
var m2 = require('./modules/module_2');
var m3 = require('./modules/module_3');

var serviceManager = {
service_1 : require('./core/service_1'),
service_2 : require('./core/service_2'),
service_3 : require('./core/service_3'),
service_4 : require('./core/service_4'),
service_5 : require('./core/service_5')
};

m1.load(serviceManager);
m2.load(serviceManager);
m3.load(serviceManager);

m1.exec();
m2.exec();
m3.exec();


And each model i put:

var serviceManager = null;

exports.load = function(services) {
serviceManager = services;
}

// some stuff...


What is the best if I gonna use that class in almost all my files?

a) Get a lot of 'require'.

b) A handle to put 'require' only one time.

c) Another solution.

Answer

I would go with a lot of requires. It does not matter, because Node.js caches the modules after first load.

From the Node.js 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.