Nodejs Application Structure

I am wondering if I am structuring my nodejs application to allow for better performance. My main problem is how I pass the application link around the modules.

Basically in my app.js file, I declare all my requirements, libraries, etc:

var app = { config : require('../../config.json'), restify : require('restify'), path : require('path'), mongo : require('mongodb'), model : require('./models.js'), step : require('step'), q : require('q'), api : require('./api_util.js'), underscore : require('underscore') }; 

In my export, I pass the entire application object. Now, given my knowledge of JavaScript (you can correct me if I am mistaken), this will not create new instances of the object, it will simply pass the object as a pointer and reference the same object in memory.

Now, what I do aside from this (for convenience) is in my recovery library (the same thing can be done with Express), I add the application value to the server request object as follows:

 app.server.pre(function (request, response, next) { request.app = app; return next(); }); 

Therefore, with every single request, if I need quick access to any of my library declarations, config, etc., I can easily access request.app. I also don’t see that this is also a problem, the same logic that the object returns a pointer back to the same memory space, so I do not double the memory usage or something else.

Is there a better / easier way to structure this?

+4
source share
1 answer

You are right about passed links instead of duplicate objects. From this point of view, you do not waste extra space when transferring links to your app .

However, I would advise you not to do this: if you pass the link to the app everywhere, then what he tells me is that you really do not know what you will need in this or that module.

You must carefully plan your dependencies and know what each module needs so that you can pass the correct dependencies for each module in your application.

Regarding things like underscore or mongodb , you should not do what you do. You should only pass modules requiring initialization. For things like underscore or mongodb , node.js caches the definition on the first require() , so you can really call require at the top of every module that it needs.

This will not result in a loss of performance, and it will clarify which library requires each module.

+6
source

Source: https://habr.com/ru/post/1414801/


All Articles