三元运算符的行为不符合预期

时间:2019-01-02 05:11:48

标签: node.js ternary-operator

my Code link

currentEnvironment = typeof (process.env.NODE_ENV === 'string') ? currentEnvironment.toLowerCase() : '';

当我传递输入 uptime-monitoring-app >> NODE_ENV=production node app.js时,它没有任何问题。

Command Line arguments :
0: /usr/local/Cellar/node@10/10.15.0/bin/node
1: /Users/tentacion/Documents/CODE/Node without NPM/uptime-monitoring-app/app.js
string

Server Started @ 5000           Environment : production
--------------------------------------------------------------------------------------------------

但对于输入uptime-monitoring-app >> Nnode app.js,它会引发错误,因为现在NODE_ENV变量现在未定义。

Command Line arguments :
0: /usr/local/Cellar/node@10/10.15.0/bin/node
1: /Users/tentacion/Documents/CODE/Node without NPM/uptime-monitoring-app/app.js
undefined
/Users/tentacion/Documents/CODE/Node without NPM/uptime-monitoring-app/envConfig.js:66
currentEnvironment = typeof (process.env.NODE_ENV === 'string') ? currentEnvironment.toLowerCase() : '';
                                                                                     ^

TypeError: Cannot read property 'toLowerCase' of undefined
    at Object.<anonymous> (/Users/tentacion/Documents/CODE/Node without NPM/uptime-monitoring-app/envConfig.js:66:86)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/Users/tentacion/Documents/CODE/Node without NPM/uptime-monitoring-app/app.js:11:19)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
  uptime-monitoring-app >>

我所期望的 如果NODE_ENV变量未定义,则表达式typeof (process.env.NODE_ENV === 'string')将为false,因此应执行下一条语句。即用空字符串分配它。

请帮助,我不知道我在做什么错。我是新来的节点

1 个答案:

答案 0 :(得分:0)

process.env.XXX始终是字符串或未定义。

更喜欢const { XXX = 'some-default-value' } = process.env之类的东西,称为对象分解,它将使用提供的XXX值,或者为它提供未定义的默认值。