为什么在process.env上定义属性会导致奇怪的条件分支?

时间:2021-09-11 23:08:19

I'm trying to test some code that does different things depending on the environment. I thought I might be able to modify properties on process.env in my tests (although I thought it might be a bad idea), but I realized I get this really odd behavior:

我正在尝试测试一些根据环境做不同事情的代码。我以为我可以在我的测试中修改process.env上的属性(虽然我认为这可能是一个坏主意),但我意识到我得到了这个非常奇怪的行为:

let foo = function(inp) {
  if (inp) {
    console.log(inp + ' -> if')
  } else {
    console.log(inp + ' -> else')
  }
}

// property starts undefined
foo(process.env.prop)
    // undefined -> else

process.env.prop = true
foo(process.env.prop)
    // true -> if

process.env.prop = false
foo(process.env.prop)
    // false -> if          !!!

process.env.prop = undefined
foo(process.env.prop)
    // undefined -> if      !!!

delete(process.env.prop)
foo(process.env.prop)
    // undefined -> else

I expected that setting process.env.prop = false would have caused the else branch to execute, not the if branch. If I use properties on new objects, I do get the behavior I expect (Link to REPL demonstrating this: https://repl.it/@JustinKulikausk/TechnologicalThickMuse).

我希望设置process.env.prop = false会导致执行else分支,而不是if分支。如果我在新对象上使用属性,我会得到我期望的行为(链接到REPL演示这个:https://repl.it/@JustinKulikausk/TechnologicalThickMuse)。

Has anyone else experienced this? I'm really hoping for some insight into why this is happening, not just a workaround for my tests.

还有其他人经历过这个吗?我真的希望能够深入了解为什么会发生这种情况,而不仅仅是我测试的解决方法。

1 个解决方案

#1


2  

Props are strings. From the docs (v10.4.1)

道具是字符串。来自文档(v10.4.1)

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.

在process.env上分配属性将隐式地将值转换为字符串。不推荐使用此行为。当值不是字符串,数字或布尔值时,Node.js的未来版本可能会抛出错误。

Your false is converted to 'false' which is "truthy" as it is a valid string of length 5. Same with keyword undefined. Your delete is legit. I'm not sure which part is deprecated, but the behavior you describe looks like it is working as expected.

你的false被转换为'false',这是“truthy”,因为它是一个长度为5的有效字符串。与关键字undefined相同。你的删除是合法的。我不确定哪个部分已弃用,但您描述的行为看起来像是按预期工作。

#1


2  

Props are strings. From the docs (v10.4.1)

道具是字符串。来自文档(v10.4.1)

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.

在process.env上分配属性将隐式地将值转换为字符串。不推荐使用此行为。当值不是字符串,数字或布尔值时,Node.js的未来版本可能会抛出错误。

Your false is converted to 'false' which is "truthy" as it is a valid string of length 5. Same with keyword undefined. Your delete is legit. I'm not sure which part is deprecated, but the behavior you describe looks like it is working as expected.

你的false被转换为'false',这是“truthy”,因为它是一个长度为5的有效字符串。与关键字undefined相同。你的删除是合法的。我不确定哪个部分已弃用,但您描述的行为看起来像是按预期工作。