__dirname is not defined in Node 14 version

Javascriptnode.js

Javascript Problem Overview


I have been using Node version 12.3.4 updated it to 14.14.0 and started to receive a lot of issues which I fixed. The only thing that I don't understand is the issue

__dirname is not defined

__dirname is a core variable in Node as I know, Is it removed in Node 14?

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

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();

Solution 3 - Javascript

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).

Solution 4 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEduardView Question on Stackoverflow
Solution 1 - Javascriptadlopez15View Answer on Stackoverflow
Solution 2 - JavascriptJiyoon HurView Answer on Stackoverflow
Solution 3 - JavascriptChrisVView Answer on Stackoverflow
Solution 4 - JavascriptNathanaelView Answer on Stackoverflow