Erdi
Erdi

Reputation: 1884

node.js command line scripts for configuration an application

file: /config/index.js;

var config = {
    local: {
        mode: 'local',
        port: 3000
    },
    staging: {
        mode: 'staging',
        port: 4000
    },
    production: {
        mode: 'production',
        port: 5000
    }
}
   module.exports = function(mode) {
        return config[mode || process.argv[2] || 'local'] || config.local;
    }

file: app.js;

...
var config = require('./config')();
...
http.createServer(app).listen(config.port, function(){
    console.log('Express server listening on port ' + config.port);
});

what is the meaning of config[mode || process.argv[2] || 'local'] || config.local; .

what I know ;
1) || mean is "or". 2) when we enter on terminal node app.js staging, process.argv[2] gets 2.argument from NODE.JS command line so it is "staging".

please, someone can explain these codes snippets ?

Upvotes: 4

Views: 222

Answers (1)

Sergio
Sergio

Reputation: 28837

First part is defining the config object. Then it exports that object.

When you call this module from another file/code you can pass a variable mode to that module. So if you call this module from another file you could do:

var config = require('/config/index.js')('staging');

Doing that you will be passing that word/string 'staging' into the variable mode wich would basically be the same as return config.staging;, or return config['staging'] to be pedagogical.

The || chain is basically like you said. If the first is falsy it will go to the next one. So, if mode is undefined, next is process.argv[2] which means it will look for extra commands given when the app was called. Like $ node index staging. That would produce the same result as explained above.

If none of those 2 are defined, local will be default! And as a safeguard: in case the config object has no property called local, or its empty it will default to config.local. That doesn't make much sense, unless the config object is different or can be changed outside the code example you posted. Otherwise its redudant, a repetition of the last or

Upvotes: 2

Related Questions