Skip to main content
2 of 2
Fixed incorrect way of converting URL to path (that breaks on Windows)
PJ Eby
  • 9k
  • 5
  • 25
  • 20

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:

import { fileURLToPath } from 'url'; const __filename = fileURLToPath(new URL(import.meta.url)); 

And for the directory containing the current module:

import { fileURLToPath } from 'url'; import path from 'path'; const __dirname = path.dirname(fileURLToPath(new URL(import.meta.url))); 
Michael Cole
  • 16.3k
  • 7
  • 90
  • 98