← coderrocketfuel.com

Get the Path of the Current Working Directory in Node.js

Do you need to get the path of the current working directory in Node.js?

Node.js has two built-in ways to do this: __dirname and the process.cwd() function.

In this article, we'll cover how to use both! And since both of those methods are built into Node.js, you won't need to install any NPM packages.

Let's get started!

Table of Contents

__dirname

The first method to get the path of the current directory is the __dirname method. This is a Node.js core module that gets the current path of whatever directory the JavaScript file or module is running in.

Here's how you use it out in the wild:

__dirname
// Prints: /Users/Billy_Bob/projects

And you can also get the same result by using the path.dirname() method combined with the __filename module.

The path.dirname() function takes a path and returns the working directory of the given path. And the __filename module is the full path of the current file.

You can combine those two methods to get the path of the current directory like this:

path.dirname(__filename)
// Prints: /Users/Billy_Bob/projects

Pretty easy, right? We'll show you one additional way to do this in the next section.

process.cwd()

The process.cwd() function returns the current working directory of the Node.js process.

Here's what the code looks like:

process.cwd()
// Prints: /Users/Billy_Bob/projects

This is a simple option and built directly into Node.js, so no NPM packages are required.