Node.js命令行脚本用于配置应用程序。

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);
});

config[mode || process.argv[2] || 'local'] || config.local; 的含义是什么?

已知信息如下:
1) || 表示 "或"。 2) 当在终端输入 node app.js staging 时,process.argv[2] 获取 NODE.JS 命令行中的第二个参数,因此它是 "staging"。

请问有人能够解释这些代码片段吗?


这个问题非常有用,为什么只因为两个基本语法问题就给了-1分呢?> . < - Erdi
你已经回答了自己的问题。||表示或者 - Ben Fortune
1个回答

2

首先定义了一个配置对象,然后将该对象导出。

当你从另一个文件/代码中调用该模块时,可以向该模块传递变量 mode。因此,如果你从另一个文件中调用该模块,可以这样做:

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

这样做,您将把单词/字符串'staging'传递到变量'mode'中,这基本上与'return config.staging;'相同,或者为了教育目的而返回config ['staging']。
'||'链基本上就像你说的一样。如果第一个是falsy,它将转到下一个。因此,如果'mode'是'undefined',接下来是'process.argv [2]',这意味着它将查找在调用应用程序时给出的额外命令。 像'$ node index staging'。这将产生与上述解释相同的结果。
如果这两个都没有定义,那么'local'将是默认值!作为保障措施:如果config对象没有名为local的属性,或者它为空,则默认为'config.local'。除非config对象在代码示例中以外不同或可以在代码之外更改,否则这没有多少意义,这是最后一个'or'的重复。

1
Sergio你太棒了,非常感谢,这是最好的解释,我什么都懂了 :) - Erdi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接