dirname and filename in nodejs es6 module

In Node.js with ES6 modules, you can use the import.meta.url to get the current file’s URL, and then use the URL module to extract the directory name and file name.

Here’s how you can do it:

Example:

import { fileURLToPath } from 'url';
import { dirname } from 'path';

// Get the current file URL
const __filename = fileURLToPath(import.meta.url);

// Get the directory name of the current file
const __dirname = dirname(__filename);

console.log('Directory:', __dirname);
console.log('Filename:', __filename);

Explanation:

  1. import.meta.url gives the file URL.
  2. fileURLToPath(import.meta.url) converts that URL to a file path.
  3. dirname(__filename) gets the directory name from the file path.

If you need to run this in an ES6 module, make sure your package.json has "type": "module".

Leave a Reply