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