__dirname 在 Node 14版本中没有定义

我一直在使用节点版本 12.3.4更新到14.14.0,并开始收到很多问题,我修复。我唯一不明白的就是这个问题

__dirname is not defined

据我所知,__dirname是 Node 中的一个核心变量,它在 Node 14中被删除了吗?

59467 次浏览

How are you loading the file? According to this issue, the problem arises if you load it as an ECMAScript module which do not contain __dirname.

https://github.com/nodejs/help/issues/2907#issuecomment-671782092

Following the documentation below you may be able to resolve the issue: https://nodejs.org/api/esm.html#esm_no_require_exports_module_exports_filename_dirname

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


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

There's usually no need to import from 'url' or 'path'.

E.g. (using ESM)

fs.readFileSync(new URL('myfile.txt', import.meta.url));

will read myfile.txt from the directory of the JavaScript file (not from the current working directory).

My code before was like below.

app.use(express.static(path.join(__dirname, 'public')));

And I got this error.

ReferenceError: __dirname is not defined in ES module scope

And I solved this by adding code below.

import path from 'path';
const __dirname = path.resolve();

A quick fix (depending on your project) would be to ensure that "type": "module" does not exist in your package.json file

Got this from above link

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


const app = express();


//we need to change up how __dirname is used for ES6 purposes
const __dirname = path.dirname(fileURLToPath(import.meta.url));
//now please load my static html and css files for my express app, from my /dist directory
app.use(express.static(path.join(__dirname ,'dist')));


//works...