Search code examples
node.jsecmascript-6es6-modules

Alternative for __dirname in Node.js when using ES6 modules


I use the flag --experimental-modules when running my Node application in order to use ES6 modules.

However when I use this flag the metavariable __dirname is not available. Is there an alternative way to get the same string that is stored in __dirname that is compatible with this mode?


Solution

  • Starting with Node.js 20.11 / 21.2, you can use import.meta.dirname:

    const __dirname = import.meta.dirname;
    

    For Node.js 10.12 and higher there's an alternative that doesn't require creating multiple files and handles special characters in filenames across platforms:

    import { dirname } from 'node:path';
    import { fileURLToPath } from 'node:url';
        
    const __dirname = dirname(fileURLToPath(import.meta.url));
    

    The built-in modules 'path' and 'url' can be optionally prefixed with the node scheme as 'node:path' and 'node:url' since Node.js 14.14.