0
0
Node.jsframework~5 mins

process.cwd and __dirname in Node.js

Choose your learning style9 modes available
Introduction

These help you find out where your program is running from. This is useful when you want to work with files or folders in your project.

When you want to read or write files relative to where you started your program.
When you need to know the folder of the current script file.
When you want to build paths that work no matter where your program runs.
When debugging to check your program's running location.
When loading configuration or assets from your project folders.
Syntax
Node.js
process.cwd()
__dirname

process.cwd() returns the current working directory where you started the Node.js process.

__dirname is a variable that holds the directory name of the current script file.

Examples
Prints the folder where you ran the Node.js command.
Node.js
console.log(process.cwd())
Prints the folder where the current script file is located.
Node.js
console.log(__dirname)
Builds a path to a file inside a 'data' folder next to the script.
Node.js
const path = require('path');
console.log(path.join(__dirname, 'data', 'file.txt'))
Sample Program

This program shows the difference between process.cwd() and __dirname. It also builds a path to a file named example.txt located in the same folder as the script.

Node.js
const path = require('path');

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

const filePath = path.join(__dirname, 'example.txt');
console.log('Path to example.txt:', filePath);
OutputSuccess
Important Notes

process.cwd() can change if you use process.chdir() to change folders during runtime.

__dirname is fixed to the script file location and does not change.

Use path.join() to safely build file paths that work on all operating systems.

Summary

process.cwd() tells you where you started your Node.js program.

__dirname tells you where the current script file lives.

Both help you work with files and folders in your project safely and clearly.