这是我能找到的关于 process.env
属性的最可靠的文档:https://nodejs.org/api/process.html#process_process_env .
它提到了 USER
,但没有提到 USERNAME
。在我的机器 (Windows/Bash) 上,当我打印 process.env
的内容时,我看到了 USERNAME
(我的 Windows 用户名)但没有看到 USER
。同样,echo $USERNAME
显示我的名字,但 echo $USER
不返回任何内容。
USER
和 USERNAME
有什么区别?是操作系统的事吗?它们可以互换吗?
最佳答案
您链接到的关于process.env
的文档显示了一个示例 环境;它并不意味着规范。 process.env
基本上可以是任何东西——它的值通常具有 shell 提供的操作系统默认值,但最终它们由用户和/或启动您的进程的进程控制。
即,用户可以运行
$ USER=lies node script.js
...并且 process.env
不会包含真实的用户名。
如果您有兴趣获取有关您的进程运行的用户的信息,请调用 os.userInfo()
,这(主要是1)跨平台一致。
> os.userInfo()
{ uid: -1,
gid: -1,
username: 'josh',
homedir: 'C:\\Users\\josh',
shell: null }
1 - 在 Windows 上,uid
、gid
和 shell
没有用,如上所示
os.userInfo()
调用 uv_os_get_passwd
,无论环境变量中的内容如何,它都会返回实际的当前有效用户。
uv_os_get_passwd
Gets a subset of the password file entry for the current effective uid (not the real uid). The populated data includes the username, euid, gid, shell, and home directory. On non-Windows systems, all data comes from getpwuid_r(3). On Windows, uid and gid are set to -1 and have no meaning, and shell is NULL.
关于node.js - Node中的 `process.env.USER`和 `process.env.USERNAME`有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48551509/