Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get filename of script being executed in NodeJS?

Tags:

node.js

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

like image 830
theZiki Avatar asked Dec 11 '12 21:12

theZiki


People also ask

What is __ filename in node?

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.

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

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.

How do I find a file in node JS?

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.


2 Answers

You can use variable __filename

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

like image 77
Hector Correa Avatar answered Sep 18 '22 06:09

Hector Correa


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); 
like image 42
Michael Cole Avatar answered Sep 18 '22 06:09

Michael Cole