Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท path, os and url

Node.js os.homedir() and os.tmpdir() methods

Reference for os.homedir() and os.tmpdir() in Node.js: find the user's home and the temporary directory, create unique temp folders and clean them up.

os.homedir() returns the current user's home directory and os.tmpdir() returns the operating system's default directory for temporary files. Both return absolute paths as strings and take no arguments.

They let a program find well-known locations without hard-coding platform-specific paths such as /home/ann, C:\Users\Ann or /tmp. Combine them with path.join() to build file names.

NODE
import os from "node:os";
import path from "node:path";

const config = path.join(os.homedir(), ".myapp", "config.json");

Try it

Node.js Absolute paths

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 A private temporary directory

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.homedir(): string
os.tmpdir(): string
Name Description
(none) Neither function takes arguments.

Returns: an absolute path string. homedir() uses the HOME environment variable on POSIX systems (and USERPROFILE on Windows) and falls back to the user database. tmpdir() honors TMPDIR, TMP and TEMP and removes a trailing slash.

Edge cases: in minimal containers or service accounts the home directory may not exist or may not be writable. The temp directory is shared by all users, so never use a predictable file name in it.

Usage notes

  • Use fs.mkdtemp() for scratch space. It creates a uniquely named directory atomically, which avoids collisions and guessing attacks.
  • Clean up yourself. Node.js never removes temp files. Delete them in a finally block or on exit.
  • Environment overrides are honored. Setting HOME before the call changes the answer on POSIX systems, which is useful for tests.
  • Do not store data you care about in tmp. The system may clear it on reboot or by age.
  • Config conventions: many tools use ~/.config/name or an XDG variable; os.homedir() is only the starting point.
  • Symlinks: tmpdir() can be a symlink (on macOS it is under /var/folders, which points into /private), so use fs.realpath() when comparing paths.