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

December 29, 2020 - 1 min read

To get the filename of the currently executing script, you can use the __filename 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 __filename environment variable like this,

scripts/myscript.js

console.log("Filename of executing script:", __filename);

If we were to execute the script using the command node scripts/myscript.js from the terminal, we would get the absolute path to the filename of the currently executing script,

Filename of executing script: /Users/melvingeorge/scripts/myscript.js

like this.

See this example live in repl.it.

Feel free to share if you found this useful 😃.