Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs app structure

I'm wondering if I'm structuring my nodejs app accordingly to account for best performance. My major concern is in regards to how I'm passing in moving my app reference around modules.

Basically in my app.js file I'm declaring all of my requires, 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 exports I'm passing in the entire app object. Now given my knowledge of JavaScript (you can correct me if I'm wrong), this will not create new instances of the object, it will simply pass in the object as a pointer and reference the same object in memory.

Now what I find myself doing aside from that (for ease) is in my restify library (the same can be done with Express), I'm appending the app value to the server request object like so:

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

Hence on every single request if I need quick access to any of my library declarations, config etc. I can easily access request.app. I don't see this being an issue either, same logic the object acts a pointer back to the same memory space, so I'm not doubling memory usage or anything.

Is there a better/easier way of structuring this?

like image 842
pilotguy Avatar asked May 29 '12 01:05

pilotguy


1 Answers

You are correct about references being passed instead of objects being duplicated. From that point of view, you are not wasting extra space when passing references to your app.

However, I would advise you against doing this: if you pass a reference to app around everywhere, what it tells me is that you don't really know what you will need in this or that module.

You should carefully plan your dependencies and know what each module will need so that you can pass the right dependencies for each module in your app.

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

This will not incur any performance loss, and it will make it clearer what library each module requires.

like image 74
ziad-saab Avatar answered Oct 04 '22 20:10

ziad-saab