node: accessing the home directory

2020-08-11

 | 

~1 min read

 | 

133 words

In Node, the os module provides platform agnostic ways to interrogate the operating system. For example, the homedir method:

Returns the string path of the current user’s home directory.

On POSIX, it uses the $HOME environment variable if defined. Otherwise it uses the effective UID to look up the user’s home directory.

On Windows, it uses the USERPROFILE environment variable if defined. Otherwise it uses the path to the profile directory of the current user.

This is convenient for CLIs that might want to work in a POSIX or Windows environment. Once attained, it can be used in conjunction with path’s resolve method navigate the filesystem with relative ease.

Example:

const fs require("fs");
const os require("os");

const HOME = os.homedir()
const targetDir = 'path/to/target/directory'

path.resolve(HOME, targetDir)


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!