Javascript 用于配置应用程序的node.js命令行脚本

Javascript 用于配置应用程序的node.js命令行脚本,javascript,node.js,Javascript,Node.js,文件:/config/index.js var config = { local: { mode: 'local', port: 3000 }, staging: { mode: 'staging', port: 4000 }, production: { mode: 'production', port: 5000 } } module.expo

文件:/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;
    }
文件: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命令行获取2.argument,因此它是“staging”


请有人解释一下这些代码片段?

第一部分是定义配置对象。然后它导出该对象

当您从另一个文件/代码调用此模块时,可以将变量
mode
传递给该模块。因此,如果您从另一个文件调用此模块,您可以执行以下操作:

var config = require('/config/index.js')('staging');
这样做,您将把单词/字符串
'staging'
传递到变量
模式
,它基本上与
return config.staging相同,或将配置['staging']返回到教学模式

|
链基本上就像你说的那样。如果第一个是falsy,它将转到下一个。因此,如果
模式
未定义
,则下一个是
进程.argv[2]
,这意味着它将查找调用应用程序时给出的额外命令。像
$node index staging
。这将产生与上述相同的结果

如果这两项都未定义,
local
将是默认值!
作为一种保护措施:如果config对象没有名为local的属性,或者其为空,那么它将默认为
config.local
。这没有多大意义,除非config对象不同,或者可以在您发布的代码示例之外进行更改。否则,它的重述,重复上一个

问题是非常有用的,为什么只为两个基本语法问题打-1分?>。你已经回答了你自己的问题
| |
的意思是
。塞尔吉奥你太棒了,非常感谢,这是最好的解释,我什么都懂:)