0
0
NodejsHow-ToBeginner · 3 min read

How to Use process.cwd in Node.js: Simple Guide

In Node.js, process.cwd() returns the current working directory from where the Node.js process was started. You use it by calling process.cwd() without any arguments to get the absolute path as a string.
📐

Syntax

The process.cwd() method has a simple syntax with no parameters. It returns a string representing the current working directory of the Node.js process.

  • process: The global object that provides information about the current Node.js process.
  • cwd(): A method that returns the current working directory path as a string.
javascript
const currentDir = process.cwd();
console.log(currentDir);
Output
/your/current/working/directory/path
💻

Example

This example shows how to use process.cwd() to print the current working directory to the console. It helps you know the folder your Node.js app is running from, which is useful for reading or writing files relative to that location.

javascript
import path from 'path';

console.log('Current working directory:', process.cwd());

// Example: create a path to a file in the current directory
const filePath = path.join(process.cwd(), 'data.txt');
console.log('File path:', filePath);
Output
Current working directory: /your/current/working/directory/path File path: /your/current/working/directory/path/data.txt
⚠️

Common Pitfalls

One common mistake is confusing process.cwd() with __dirname. process.cwd() returns the directory where you started the Node.js process, while __dirname gives the directory of the current script file.

Another pitfall is assuming process.cwd() never changes. It can change if your code calls process.chdir(), so be careful when relying on it.

javascript
// Wrong: assuming __dirname and process.cwd() are the same
console.log('__dirname:', __dirname);
console.log('process.cwd():', process.cwd());

// Right: use the one that fits your need
// Use __dirname for script location
// Use process.cwd() for where the app was started
Output
__dirname: /your/script/file/directory process.cwd(): /your/current/working/directory/path
📊

Quick Reference

  • Use: process.cwd() to get the current working directory path as a string.
  • Returns: Absolute path string of the folder where Node.js was started.
  • Difference: process.cwd() vs __dirname (script location).
  • Change directory: You can change the working directory with process.chdir(path).

Key Takeaways

Use process.cwd() to get the absolute path of the current working directory where Node.js started.
process.cwd() returns a string and takes no arguments.
Do not confuse process.cwd() with __dirname; they serve different purposes.
The working directory can change during runtime if process.chdir() is called.
Use process.cwd() when you need paths relative to where the app was launched.