How to get filename of script being executed in NodeJS application?
The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.
We can get the path of the present script in node. js by using __dirname and __filename module scope variables. __dirname: It returns the directory name of the current module in which the current script is located. __filename: It returns the file name of the current module.
To find the files that match a pattern using Node. js, install and use the glob module, passing it a pattern as the first parameter and a callback function as the second. The function gets called with a potential error object as the first parameter and the matching files as the second.
You can use variable __filename
http://nodejs.org/docs/latest/api/globals.html#globals_filename
Use the basename
method of the path
module:
var path = require('path'); var filename = path.basename(__filename); console.log(filename);
Here is the documentation the above example is taken from.
As Dan pointed out, Node is working on ECMAScript modules with the "--experimental-modules" flag. Node 12 still supports __dirname
and __filename
as above.
If you are using the --experimental-modules
flag, there is an alternative approach.
The alternative is to get the path to the current ES module:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
import path from 'path'; const __dirname = path.dirname(new URL(import.meta.url).pathname);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With