Skip to content
Tutorials Center
My learning

Topics

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.

NODE
import os from "node:os";

const { username, homedir } = os.userInfo();
console.log(username, homedir);

Try it

Node.js Fields of the result

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.

Node.js Strings and buffers

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

NODE
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/catch and fall back to process.getuid() and environment variables.
  • homedir here is from the user database. os.homedir() prefers the HOME environment variable, so the two can differ.
  • Windows returns -1 for uid and gid, and null for shell.
  • Effective versus real user: userInfo() reports the effective user of the process. After process.setuid() it reflects the change.
  • Do not rely on username for 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.