Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `process.env.USER` and `process.env.USERNAME` in Node?

This is the most robust documentation I can find for the process.env property: https://nodejs.org/api/process.html#process_process_env.

It mentions USER, but not USERNAME. On my machine (Windows/Bash), when I print the contents of process.env, I see USERNAME (my windows username) but not USER. Similarly, echo $USERNAME shows my name but echo $USER returns nothing.

What is the difference between USER and USERNAME? Is it an operating system thing? Are they interchangeable?

like image 511
Katie Fritz Avatar asked Jan 31 '18 21:01

Katie Fritz


People also ask

What is process env in Node?

In Node. js, process. env is a global variable that is injected during runtime. It is a view of the state of the system environment variables. When we set an environment variable, it is loaded into process.

Where is process env stored in Node js?

Environment variables are stored in your system shell that you start node. js from. They are a shell feature that node. js can read/modify.

What are environment variables in Node?

Environment variables provide information about the environment in which the process is running. We use Node environment variables to handle sensitive data like passwords, which we shouldn't hard code, or configuration details that might change between runs, like what port a server should listen on. In Node.


1 Answers

The documentation about process.env that you linked to shows an example environment; it is not meant to be normative. process.env can be basically anything -- its values generally have OS defaults provided by the shell, but ultimately they are controlled by the user and/or the process that launched your process.

ie, a user could run

$ USER=lies node script.js

...and process.env would not contain the real username.


If you're interested in getting information about the user your process is running as, call os.userInfo(), which is (mostly1) consistent across platforms.

> os.userInfo()
{ uid: -1,
  gid: -1,
  username: 'josh',
  homedir: 'C:\\Users\\josh',
  shell: null }

1 - on Windows, uid, gid, and shell are useless, as seen above

os.userInfo() calls uv_os_get_passwd, which returns the actual current effective user, regardless of what's in environment variables.

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.

like image 126
josh3736 Avatar answered Sep 21 '22 22:09

josh3736