Node.js — Retrieve the Path to the User’s Home Directory

Creating applications sometimes require you to store a state for a specific user. For example, when working with a command-line application, like npm, you only want to sign in once and NPM should remember your personal access token.

Storing a personal access token for a CLI should happen in your user’s home directory. This is the place only you should have access to.

This tutorial shows you how to retrieve the user’s home directory in a Node.js script.

Node.js Series Overview

Get the User’s Home Directory Path

Node.js comes with the os core module allowing you to retrieve data from the operating system (OS). Node.js resolves this OS data depending on your operating system. For example, it returns file paths using a backslash \ on Windows and using a forward slash / on UNIX-based systems.

One of the available methods is os.homedir() returning the string path of the current user’s home directory:

const Os = require('os')

os.homedir()  
// "/Users/marcus"

Use the @supercharge/filesystem Package

I’m the maintainer of the @supercharge/filesystem package providing convenient file system utilities. The @supercharge/filesystem package comes with a handy Fs.homeDir() method resolving the home directory path:

const Fs = require('@supercharge/filesystem')

await Fs.homeDir()  
// "/Users/marcus"

The Fs.homeDir(path?) method accepts an optional path parameter allowing you to create a specific path inside of a user’s home directory. For example, you can generate a path to a settings file like this:

const Fs = require('@supercharge/filesystem')

await Fs.homeDir('.my-app/settings.yml')  
// "/Users/marcus/.my-app/settings.yml"

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.