Support Online
Skip to main content

Using __dirname and File Path Management in Node.js

What Will You Learn in This Guide?

In this guide, you will learn how to manage file paths in Node.js projects environment-independent and error-free.
The logic of the variable __dirname, the difference process.cwd() and its ES Modules counterpart are discussed simply.

Technical Summary

  • Topic: Node.js __dirname and file path management
  • Purpose: To permanently prevent file not found errors
  • Solved Problem: Corrupted paths when run from different directories
  • Scope: CommonJS, ES Modules, path module

__dirname What is it and Why is it Important?

__dirname returns the physical folder path of the JavaScript file it is located in.
It doesn't depend on where the command is run from.

Example file path:

/home/genixnode/project/app.js

go

__dirname output:

/home/genixnode/project

yaml

This feature provides reliable reference for configuration files and static assets.


Critical Difference: __dirname vs process.cwd()

These two concepts are often confused.

  • __dirname
    Shows the folder where the file is located.
    It is unchanging and constant.

  • process.cwd()
    Indicates the directory where the Node.js process was started.
    Varies depending on terminal location.

Example scenario:

node ./src/app.js

1. process.cwd() → project home directory

2. __dirname → src folder

  • __dirname should always be used when accessing in-file resources.

Creating a Secure Path with the #### path Module

  1. Do not create file paths with string concatenation.

// Yanlış
const yol = __dirname + '/veriler/ayar.json';

Right approach:


const path = require('path');

const yol = path.join(__dirname, 'veriler', 'ayar.json');
  • This method ensures Windows and Linux compatibility.

Difference between path.join() and path.resolve()

  1. path.join()
  • Assembles parts safely.

2.path.resolve()

  • Always produces absolute path.

  • __dirname + path.join() should be preferred for file-based operations.

  1. __dirname in ES Modules (ESM) Environment
  2. __dirname is not present by default when using ES Modules.


ReferenceError: __dirname is not defined

Standard solution:


import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const configYolu = join(__dirname, 'config', 'genixnode.json');
  • This method complies with standards and can be used safely.

Practical Usage Scenarios

Uploading Configuration File


const fs = require('fs');
const path = require('path');

const configYolu = path.join(__dirname, 'config', 'sunucu-ayarlari.json');
const ayarlar = JSON.parse(fs.readFileSync(configYolu, 'utf8'));
  • The correct file is loaded no matter where the application is launched.

Log Directory Management

const fs = require('fs');
const path = require('path');

const logDizini = path.join(__dirname, 'loglar');
fs.mkdirSync(logDizini, { recursive: true });

fs.appendFileSync(
path.join(logDizini, 'app.log'),
'Sunucu başlatıldı.\n'
);
  • PM2 behaves consistently across systemd and CI environments.

Frequently Asked Questions

1. Does __dirname work the same on Windows and Linux? The logic is the same, path.join() solves the separator difference.

2. Why is process.cwd() not enough? The working directory may change, file paths become corrupted.

3. Is __dirname used on the frontend? No. It exists only in the Node.js server environment.

4. How do bundlers (Vite, Webpack) handle this? They convert during compilation, there is no runtime file system.


Result

__dirname is the most reliable reference for file paths in Node.js projects. Knowing the equivalent of ES Modules reduces the risk of errors in modern projects. Applications become portable when used with the path module.

You can safely apply this approach in Node.js projects on the GenixNode infrastructure.