DEV Community

Cover image for How to get the filename of the currently executing script in Node.js?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

like this.

See this example live in repl.it.

Feel free to share if you found this useful 😃.


Top comments (0)