Alternative for __dirname in node when using the --experimental-modules flag

前端 未结 9 1877
旧时难觅i
旧时难觅i 2020-12-01 06:03

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

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 06:40

    I used:

    import path from 'path';
    
    const __dirname = path.resolve(path.dirname(decodeURI(new URL(import.meta.url).pathname)));
    

    decodeURI was important: used spaces and other stuff within the path on my test system.

    path.resolve() handles relative urls.

    edit:

    fix to support windows (/C:/... => C:/...):

    import path from 'path';
    
    const __dirname = (() => {let x = path.dirname(decodeURI(new URL(import.meta.url).pathname)); return path.resolve( (process.platform == "win32") ? x.substr(1) : x ); })();
    

提交回复
热议问题