Node.js: filename and dirname


How do you get the filename and directory name of a Node.js module?

__filename

With __filename, you can get the filename of a module:

// /path/to/file.js
console.log(__filename); // /path/to/file.js

__dirname

With __dirname, you can get the directory name of a module:

// /path/to/file.js
console.log(__dirname); // /path/to

filename

What if you want the filename without the full path?

// /path/to/file.js
const path = require('path');
console.log(
  path.basename(__filename) // file.js
);

parent

To get the parent filename that required the module, use require.main.filename:

// /path/to/parent.js
require('/path/to/child.js');
// /path/to/child.js
console.log(
  require.main.filename // /path/to/parent.js
);


Please support this site and join our Discord!