DEV Community

flavio ⚑️πŸ”₯
flavio ⚑️πŸ”₯

Posted on β€’ Originally published at flaviocopes.com on

3 3

Get the current folder in Node

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.

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more β†’

Top comments (0)

AI Agent image

How to Build an AI Agent with Semantic Kernel (and More!)

Join Developer Advocate Luce Carter for a hands-on tutorial on building an AI-powered dinner recommendation agent. Discover how to integrate Microsoft Semantic Kernel, MongoDB Atlas, C#, and OpenAI for ingredient checks and smart restaurant suggestions.

Watch the video πŸ“Ί