How to get filename of script being executed in NodeJS?

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

Answers


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);

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


Need Your Help

Image resizing algorithm

algorithm image resize

I want to write a function to downsize an image to fit specified bounds. For example i want to resize a 2000x2333 image to fit into 1280x800. The aspect ratio must be maintained. I've come up with ...