islishude / blog

my web notes
https://islishude.github.io/blog/
101 stars 15 forks source link

node.js 中的 process.env 遇到的坑 #175

Closed islishude closed 6 years ago

islishude commented 6 years ago

有这么一段代码,是否会有打印输出 “hello,world” ?

process.env.dev = false;

if(process.env.dev){
    console.log("hello,world");
}

答案是会。

因为 process.env 给任何属性赋值都会先转化为字符串,而字符串在强制转化成布尔值是 true,所以回打印输出。

image

来自官方文档,值得注意的是,以后不可以再给process.env的属性赋值为非字符串类型,否则会再将来的版本中报错。

Assigning a property on process.env will implicitly convert the value to a string. This behavior is deprecated. Future versions of Node.js may throw an error when the value is not a string, number, or boolean.

有空还得多看官方文档啊。

greatghoul commented 6 years ago

长见识了。

islishude commented 6 years ago

move to https://islishude.github.io/blog/2018/08/01/nodejs/node-js-%E4%B8%AD%E7%9A%84-process-env-%E9%81%87%E5%88%B0%E7%9A%84%E5%9D%91/