Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__dirname is not defined in Node 14 version

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?

like image 768
Eduard Avatar asked Oct 16 '20 06:10

Eduard


People also ask

What is __ dirname in node?

In Node. js, __dirname is always the directory in which the currently executing script resides (see this).

What is the local __ dirname variable in a node JS module?

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file. It returns the name the of current working directory. It returns the directory name of the directory containing the source code file.

What is __ dirname in Webpack?

__dirname returns the the directory name of the current module. Let's take a look at some code that uses __dirname . Without webpack. This is what the output of it looks like.


2 Answers

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(); 
like image 25
Jiyoon Hur Avatar answered Sep 19 '22 15:09

Jiyoon Hur


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); 
like image 120
adlopez15 Avatar answered Sep 20 '22 15:09

adlopez15