How to get the directory of the currently executing script in Node.js?

December 28, 2020 - 1 min read

To get the directory of the currently executing script, you can use the __dirname environment variable in Node.js

For example, let's say we have a file called myscript.js inside a directory called scripts.

Inside this myscript.js file let's log the value of the __dirname environment variable like this,

scripts/myscript.js

console.log("Script executing in directory:", __dirname);

If we were to execute the script using the command node scripts/myscript.js from the terminal, we would get the full absolute path to the directory holding the script file

Script executing in directory: /Users/bob/scripts

like this.

See this example live in repl.it.

Feel free to share if you found this useful 😃.