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'
console.log(__dirname)
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'
console.log(__filename)
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'
console.log(process.cwd())
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).

Sources

https://attacomsian.com/blog/nodejs-get-current-directory
https://stackoverflow.com/questions/9080085/node-js-find-home-directory-in-platform-agnostic-way
https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js

Latest comments (0)