How to get the directory of the currently executing script in Node.js?
Published December 28, 2020
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
myscript.js file let's log the value of the
__dirname environment variable like this,
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
See this example live in repl.it.