Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

__dirname is not defined in Node 14 version

Writer Sebastian Wright

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?

2

4 Answers

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.

Following the documentation below you may be able to resolve the issue:

import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
3

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

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

4

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy