52

How to get filename of script being executed in NodeJS application?

theZiki
  • 939
  • 1
  • 8
  • 14

3 Answers3

56

You can use variable __filename

http://nodejs.org/docs/latest/api/globals.html#globals_filename

Brad
  • 159,648
  • 54
  • 349
  • 530
Hector Correa
  • 26,290
  • 8
  • 57
  • 73
  • 3
    This is only useful if you want to know the filename currently running the code that is looking at the `__filename` variable. If, instead, you need to know the name of the entire nodejs program that is running, use @Brad 's answer below. – Alan Mimms Oct 04 '16 at 22:25
  • 3
    This [no longer works with ES modules](https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js/50053801#50053801). – Dan Dascalescu Apr 25 '19 at 00:44
27

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);
Michael Cole
  • 15,473
  • 7
  • 79
  • 96
  • This [no longer works with ES modules](https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js/50053801#50053801). – Dan Dascalescu Apr 25 '19 at 00:44
23

You need to use process.argv. In there will be the name of the script that was executed from the command line, which can be different than what you will find in __filename. Which is appropriate depends on your needs.

http://nodejs.org/docs/latest/api/process.html#process_process_argv

Brad
  • 159,648
  • 54
  • 349
  • 530
  • how is it different than `__filename`? It looks the same. – 1252748 Nov 06 '17 at 20:03
  • 2
    @1252748 You should read the documentation: https://nodejs.org/docs/latest/api/modules.html#modules_filename `__filename` is the name of the file you're currently in. If I have a script that includes 5 other modules, there are 6 different possibilities of what `__filename` will be, depending on where I checked. Furthermore, the script might have a symlink that was used to execute it. `process.argv` will give you what was actually ran. – Brad Nov 06 '17 at 21:25
  • Be careful, be what was actually executed may not be where your script is actually located. In other words, it might be a symlink instead. – starbeamrainbowlabs Mar 16 '19 at 20:54