Node.js Reference ยท path, os and url
Node.js os.userInfo() method
Reference for os.userInfo() in Node.js: read the username, uid, gid, shell and home directory of the current user, with encoding and platform notes.
os.userInfo() returns an object describing the user account that owns the running process: user name, numeric user and group IDs, login shell and home directory. It reads the system user database, so it works even when environment variables such as USER are not set.
It is useful for log messages, permission checks and choosing per-user directories. On POSIX systems the numeric IDs are real; on Windows uid and gid are -1 and shell is null.
import os from "node:os"; const { username, homedir } = os.userInfo(); console.log(username, homedir);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
os.userInfo(options?: { encoding?: string }): { uid: number, gid: number, username: string | Buffer, homedir: string | Buffer, shell: string | Buffer | null }
| Name | Description |
|---|---|
options.encoding |
Character encoding for the string fields. Defaults to 'utf8'. Use 'buffer' to receive Buffer objects, which is useful for names that are not valid UTF-8. |
Returns: an object with the fields above.
Errors: a SystemError is thrown if the process has no entry in the user database (it happens in some containers that run with an arbitrary numeric user ID).
Usage notes
- Catch the error in containers. If your service might run as an unnamed UID, wrap the call in
try/catchand fall back toprocess.getuid()and environment variables. homedirhere is from the user database.os.homedir()prefers theHOMEenvironment variable, so the two can differ.- Windows returns
-1foruidandgid, andnullforshell. - Effective versus real user:
userInfo()reports the effective user of the process. Afterprocess.setuid()it reflects the change. - Do not rely on
usernamefor authorization. It is a label; compare numeric IDs where permissions matter. - Privacy: avoid sending the result in telemetry, because the home directory and user name are personal data.