How do I get the path to the current script with Node.js?

Better Stack Team
Updated on March 11, 2024

In Node.js, you can use the __filename variable to get the absolute path to the current script file, and __dirname to get the absolute path to the directory containing the current script. Here's an example:

 
console.log('__filename:', __filename);
console.log('__dirname:', __dirname);

When you run this script, it will print the absolute path to the current script file and the directory containing the script.

Keep in mind that __filename returns the absolute path to the current module (script), and __dirname returns the absolute path to the directory containing the current module.

For example, if your script is located at /path/to/your/script.js, running the above code would output something like:

 
__filename: /path/to/your/script.js
__dirname: /path/to/your

These variables are particularly useful when you need to construct paths relative to the location of your script or when working with file I/O operations.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.