使用--experimental-modules标志时,节点中__dirname的替代方法 [英] Alternative for __dirname in node when using the --experimental-modules flag

查看:171
本文介绍了使用--experimental-modules标志时,节点中__dirname的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在运行节点应用程序时使用标志--experimental-modules,以便使用ES6模块.

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

但是,当我使用此标志时,元变量__dirname不可用.是否有另一种方法来获取与该模式兼容的存储在__dirname中的相同字符串?

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?

推荐答案

从Node.js 10.12开始,有一种替代方案不需要跨平台创建多个文件并处理文件名中的特殊字符:

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

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

const __dirname = dirname(fileURLToPath(import.meta.url));

这篇关于使用--experimental-modules标志时,节点中__dirname的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆