Course contentsShow
← JavaScript
Lesson 1499 of 2,72333. JavaScript in Node.jsFree lesson

Process.cwd() and Process.chdir()

Getting and changing the current working directory of the Node.js process.

Process.cwd() and Process.chdir()

You'll learn how to get and change the current working directory of your Node.js process.

What is the Current Working Directory?

When your Node.js program runs, it operates from a specific folder on your computer—this is the current working directory (cwd). It's the reference point for relative file paths. Think of it like the folder you're "standing in" when you run your script.

Getting the Current Directory with Process.cwd()

The process.cwd() method returns a string containing the absolute path of the directory from which Node.js was launched:

console.log(process.cwd());
// Example output: '/Users/yourname/projects/myapp'

This is particularly useful when you need to build file paths or understand where your program is running from.

Changing the Directory with Process.chdir()

The process.chdir() method changes the current working directory. Pass it a path as a string:

console.log(process.cwd());
// '/Users/yourname/projects/myapp'

process.chdir('/tmp');

console.log(process.cwd());
// '/tmp'

Why This Matters

Understanding the working directory is crucial for file operations. If your script tries to read ./data.json, Node.js looks for that file relative to the current working directory, not necessarily where your script file is located. If you run node src/app.js from your project root, the cwd is the root, not the src folder.

Changing directories can be useful when your program needs to work with files in different locations, though it's generally safer to use absolute paths instead.

Key Takeaway: process.cwd() tells you where your Node.js process is running from, while process.chdir() lets you change that location—both are essential for managing file paths correctly.