Nodejs__dirname

How and When to Use "Nodejs __dirname"

Written by: Alexandra Anderson

Alexandra Anderson

Alexandra is a web marketer, Agile Product Owner, and die-hard wordsmith who's contributed to HostingAdvice, InMotion Hosting, HostGator, and other prominent hosting and technology blogs, as well as Forbes. She has a master's degree in information technology from Virginia Tech and more than 10 years of experience building websites, advising on web and mobile app design, and crafting content that engages and converts. Her primary subject matter expertise spans WordPress, UX design, Agile project management, and, of course, web hosting.

See full bio »

Edited by: Lillian Castro

Lillian Castro

Lillian brings more than 30 years of editing and journalism experience to our team. She has written and edited for major news organizations, including The Atlanta Journal-Constitution and the New York Times, and she previously served as an adjunct instructor at the University of Florida. Today, she edits HostingAdvice content for clarity, accuracy, and reader engagement.

See full bio »

Sometimes when working in Node, you want to find the directory of the file you’re currently executing or the directory from which the Node command was called. This can be useful when requiring other files, reading or writing logs, and executing various filesystem-level functions.

There are at least three ways to refer to the current directory in Node:

It’s important to note the differences in each method, and we’ll cover how and when to use __dirname in Node.js using examples below.

Examples of Finding Node.js Paths Using __dirname

The global variable __dirname, which is the same as the path.dirname() function of the __filename, will give you the directory in which the executing file is located.

Let’s walk through a few hypotheticals to illustrate how __dirname and process.cwd() function in different directories of your application. We’ll create a simple tree structure for our examples next.

Creating a Directory Tree Structure for Our Examples

You can copy the lines below into your terminal and hit ENTER:

mkdir -p /tmp/myapp/subdir  cd /tmp/myapp  echo "  console.log('__dirname (the directory of the script file): ', __dirname);  console.log('process.cwd() (the directory from which the script file was called): ', process.cwd());  " > app.js  cp app.js subdir/

Now we have two identical app.js scripts in two directories: one in the root directory of “myapp” and another in a subdirectory called subdir.

    myapp/      app.js      subdir/        app.js  

Let’s see what output we get when we run the app.js script at different locations.

Example 1: In the Root Directory

Running root directory app.js from the root directory, we get:

  $ cd /tmp/myapp  $ node app.js   __dirname (the directory of the script file): /tmp/myapp  process.cwd() (the directory from which the script file was called): /tmp/myapp  

You’ll notice there is no difference between the two methods here.

Example 2: In a Buried Directory

Running subdirectory app.js from the subdirectory, we get:

  $ cd subdir/  $ node app.js   __dirname (the directory of the script file): /tmp/myapp/subdir  process.cwd() (the directory from which the script file was called): /tmp/myapp/subdir  

Again, we see no difference.

Example 3: Executing a Script Within A Directory Other Than The Current Directory

Running the root directory app.js from the subdirectory, we get:

  $ node ../app.js   __dirname (the directory of the script file): /tmp/myapp  process.cwd() (the directory from which the script file was called): /tmp/myapp/subdir  

Here, we see __dirname is different from process.cwd(), because __dirname uses the location of the executing script file, which is in a directory other than the current directory.

Bonus: 2 Other Ways to Refer to File Directories in Node.js

As I referenced earlier, there are two other ways of referring to directories in Node:

  1. Dot Notation (./ and ../) refers to the directory of the called Node command.
  2. process.cwd() refers back to the directory of the called Node command.

For example:

var fs = require('fs');  console.log(fs.existsSync('./app.js'));  // This prints "true" if you are in the myapp directory  

Note: Calling process.cwd() is the same as using the dot notion (./), except when using require(), which always works relative to the currently executing file.

Also, on Microsoft Windows computers, the file paths are constructed with backslashes instead of forward slashes. So, for portability reasons, we recommend you use the path module to construct relative file paths.

Advertiser Disclosure

HostingAdvice.com is a free online resource that offers valuable content and comparison services to users. To keep this resource 100% free, we receive compensation from many of the offers listed on the site. Along with key review factors, this compensation may impact how and where products appear across the site (including, for example, the order in which they appear). HostingAdvice.com does not include the entire universe of available offers. Editorial opinions expressed on the site are strictly our own and are not provided, endorsed, or approved by advertisers.

Our Editorial Review Policy

Our site is committed to publishing independent, accurate content guided by strict editorial guidelines. Before articles and reviews are published on our site, they undergo a thorough review process performed by a team of independent editors and subject-matter experts to ensure the content’s accuracy, timeliness, and impartiality. Our editorial team is separate and independent of our site’s advertisers, and the opinions they express on our site are their own. To read more about our team members and their editorial backgrounds, please visit our site’s About page.

ABOUT THE AUTHOR

Alexandra Anderson’s interest in website administration was sparked in her teens, priming her for a fast-paced career in managing, building, and contributing to online brands, including HostingAdvice, Forbes, and the blogs of prominent hosting providers. She brings firsthand experience reviewing web hosts, perfecting website design, optimizing content, and walking site owners through the steps that add up to a successful online presence. With a master's degree in information technology from Virginia Tech, she combines her extensive writing experience and technical understanding to unpack some of the most complex topics that daunt novice website owners, as well as the subjects that excite veteran technologists within the HostingAdvice readership.

« BACK TO: HOW-TO
Follow the Experts
We Know Hosting

$

4

8

,

2

8

3

spent annually on web hosting!

Hosting How-To Guides