node get path of current file

To get the path of the current file in Node.js, you can use the __filename variable. Here are the steps to do it:

  1. First, you need to require the built-in path module in Node.js. This module provides utilities for working with file and directory paths.
const path = require('path');
  1. Next, you can use the path.dirname() method to retrieve the directory name of the current file. Pass __filename as the argument to get the directory name.
const currentDirectory = path.dirname(__filename);
  1. If you also want to get the file name of the current file, you can use the path.basename() method. Pass __filename as the first argument and 'js' as the second argument to get the file name with the extension.
const currentFile = path.basename(__filename, '.js');
  1. Finally, if you want to get the file name without the extension, you can omit the second argument in the path.basename() method.
const currentFileWithoutExtension = path.basename(__filename);

By following these steps, you can retrieve the path, directory name, file name, and file name without the extension of the current file in Node.js.