Tutorial

How To Use __dirname in Node.js

Updated on December 6, 2021
authorauthor

William Le and Natalia Vargas-Caba

How To Use __dirname in Node.js

Introduction

__dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file.

In this article, you will explore how to implement __dirname in your Node.js project.

Deploy your Node applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

Prerequisites

To complete this tutorial, you will need:

This tutorial was verified with Node.js v17.2.0 and npm v8.2.0.

Step 1 — Setting Up the Project

This tutorial will use the following sample directory structure to explore how __dirname works:

dirname-example
  ├──index.js
  ├──public
  ├──src
  │  ├──helpers.js
  │  └──api
  │      └──controller.js
  ├──cronjobs
  │  └──hello.js
  └──package.json

You can start by creating a dirname-example directory in your terminal:

  1. mkdir dirname-example

Navigate to the project directory:

  1. cd dirname-example

Initialize it as a Node.js project:

  1. npm init --yes

Now, you will create the directories and files to experiment with.

Step 2 — Using __dirname

You can use __dirname to check on which directories your files live.

Create and edit controller.js in the api subdirectory in the src directory:

src/api/controller.js
console.log(__dirname)      // "/Users/Sam/dirname-example/src/api"
console.log(process.cwd())  // "/Users/Sam/dirname-example"

Then, run the script:

  1. node src/api/controller.js

Create and edit hello.js in the cronjobs directory:

cronjobs/hello.js
console.log(__dirname)     // "/Users/Sam/dirname-example/cronjobs"
console.log(process.cwd()) // "/Users/Sam/dirname-example"

Then, run the script:

  1. node cronjobs/hello.js

Notice that __dirname has a different value depending on which file you console it out. The process.cwd() method also returns a value, but the project directory instead. The __dirname variable always returns the absolute path of where your files live.

Step 3 — Working With Directories

In this section, you will explore how to use __dirname to make new directories, point to them, as well as add new files.

Making New Directories

To create a new directory in your index.js file, insert __dirname as the first argument to path.join() and the name of the new directory as the second:

index.js
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, '/pictures');

fs.mkdirSync(dirPath);

Now you’ve created a new directory, pictures, after calling on the mdirSync() method, which contains __dirname as the absolute path.

Pointing to Directories

Another unique feature is its ability to point to directories. In your index.js file, declare a variable and pass in the value of __dirname as the first argument in path.join(), and your directory containing static files as the second:

index.js
express.static(path.join(__dirname, '/public'));

Here, you’re telling Node.js to use __dirname to point to the public directory that contains static files.

Adding Files to a Directory

You may also add files to an existing directory. In your index.js file, declare a variable and include __dirname as the first argument and the file you want to add as the second:

index.js
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, '/pictures');

fs.openSync(filePath, 'hello.jpeg');

Using the openSync() method will add the file if it does not exist within your directory.

Conclusion

Node.js provides a way for you to make and point to directories. And add files to existing directories with a modular environment variable.

For further reading, check out the Node.js documentation for __dirname, and the tutorial on using __dirname in the Express.js framework.

DigitalOcean provides multiple options for deploying Node.js applications, from our simple, affordable virtual machines to our fully-managed App Platform offering. Easily host your Node.js application on DigitalOcean in seconds.

Learn more here

About the authors
Default avatar
William Le

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

This is a great article, but it doesn’t answer WHY we need to use __dirname in the first place? Usually we just do “./” to access current directory.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.