Skip to content

How to get the current folder in Node

The two ways of referencing the filesystem: ./ and __dirname, explained

There are basically two ways to reference the current folder in a Node.js script:

  • ./
  • __dirname

Along with ./, there is ../, which points to the parent folder. They behave in the same way.

There is a big difference between the two.

Using __dirname in a Node script will return the path of the folder where the current JavaScript file resides.

Using ./ will give you the current working directory. It will return the same result as calling process.cwd().

Initially the current working directory is the path of the folder where you ran the node command, but that can be changed during the execution of your script, by using the process.chdir() API.

There is just one place where ./ refers to the current file path, and it's in a require() call. In there, ./ (for convenience) will always refer to the JavaScript file path, letting you import other modules based on the folder structure.

→ Download my free Node.js Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about node: