4

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 ?

2
  • question is very useful , why gave -1 point just for two basic grammer issue ? >.< Commented Nov 13, 2014 at 11:45
  • You've answered your own question. || means or. Commented Nov 13, 2014 at 11:46

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Sergio you are great , thank you very much , this is the best explanation , i understand everything :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.