DEV Community

Cover image for Get the Current Directory in node.js
Jonas Schumacher
Jonas Schumacher

Posted on


Get the Current Directory in node.js

These quick tips are small snippets that come up again and again in my work, for which I want a permantent and central place to retrieve them.

Here's the situation: You want your node script to interact with a file that is relative to its location. To do that, you need a way to determine that location.

To get the absolute path to a module, you can use the global __dirname variable.

For the follwing snippets, suppose you run the module /home/urname/code/script/main.js

// this will print '/home/urname/code/script'
Enter fullscreen mode Exit fullscreen mode

If you want the filename included as well, __filename will do the trick.

// this will print '/home/urname/code/script/main.js'
Enter fullscreen mode Exit fullscreen mode

Get the current working directory

Since it fits the topic somewhat, here's a small bonus: If you want to get the directory from which you called the script, you can use process.cwd() to do that.

Suppose you call /home/urname/code/script/main.js from the command line while you are inside /home/urname/code/temp:

// this will print '/home/urname/code/temp'
Enter fullscreen mode Exit fullscreen mode

Get the directory of the main script

Finally, if you write a plug-in and need to know the path of the main script, you can use require('path').dirname(require.main.filename).


Top comments (0)

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another “Coder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.