How to fix “__dirname is not defined in ES module scope“

I stumbled on this error while I used __dirname inside a ES module.

In an ES module, you cannot use __dirname.

Using __dirname in a Node script you can get the path of the folder where the current JavaScript file resides, and many Node.js projects use this.

But if you use it inside an ES module, you can’t use this, as the infamous “__dirname is not defined in ES module scope” error shows up.

What can you do in this case?

I solved this problem by using a solution I found on the Node.js GitHub issues.

You first need to import the Node.js path module and the fileURLToPath function from the url module:

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

Then you can replicate the functionality of __dirname in this way:

const __filename = fileURLToPath(import.meta.url);

const __dirname = path.dirname(__filename);

This, incidentally, also replicates __filename, which returns the filename of the code which is executed.

Now you can use __dirname as usual:

console.log(__dirname)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值