Node.js module filename and dirname


How do we get the directory and file name of a Node.js module?

With __dirname we can get the directory name of a module:

// `/path/to/file1.js`

console.log(__dirname); // `/path/to`

With __filename we can get the file name of a module:

// `/path/to/file1.js`

console.log(__filename); // `/path/to/file1.js`

What if we only want the name of the file and not the full path?

// `/path/to/file1.js`

var path = require('path');
console.log(
    path.basename(__filename) // `file1.js`
);

Lastly, you can get the name of the parent file that required the current module with require.main.filename:

// `/path/to/file1.js`

require('/path/to/file2.js')
// `/path/to/file2.js`

console.log(
    require.main.filename // `/path/to/file1.js`
);