The __dirname or __filename global variables are not available in ECMAScript module files. To solve the "__dirname is not defined in ES module scope" error, import and use the dirname() method from the path module. The dirname method takes a path as a parameter and returns the directory name of the path. Copied!
__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.
To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.
The path. dirname() method returns the directories of a file path.
__dirname
is only defined in scripts. It's not available in REPL.
try make a script a.js
console.log(__dirname);
and run it:
node a.js
you will see __dirname
printed.
Added background explanation: __dirname
means 'The directory of this script'. In REPL, you don't have a script. Hence, __dirname
would not have any real meaning.
Building on the existing answers here, you could define this in your REPL:
__dirname = path.resolve(path.dirname(''));
Or:
__dirname = path.resolve();
If no
path
segments are passed,path.resolve()
will return the absolute path of the current working directory.
Or @Jthorpe's alternatives:
__dirname = process.cwd();
__dirname = fs.realpathSync('.');
__dirname = process.env.PWD
If you are using Node.js modules, __dirname
and __filename
don't exist.
From the Node.js documentation:
No require, exports, module.exports, __filename, __dirname
These CommonJS variables are not available in ES modules.
require
can be imported into an ES module usingmodule.createRequire()
.Equivalents of
__filename
and__dirname
can be created inside of each file viaimport.meta.url
:
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
https://nodejs.org/docs/latest-v15.x/api/esm.html#esm_no_filename_or_dirname
In ES6 use:
import path from 'path';
const __dirname = path.resolve();
also available when node is called with --experimental-modules
As @qiao said, you can't use __dirname
in the node repl. However, if you need need this value in the console, you can use path.resolve()
or path.dirname()
. Although, path.dirname()
will just give you a "." so, probably not that helpful. Be sure to require('path')
.
I was also trying to join my path using path.join(__dirname, 'access.log')
but it was throwing the same error.
Here is how I fixed it:
I first imported the path package and declared a variable named __dirname
, then called the resolve
path method.
In CommonJS
var path = require("path");
var __dirname = path.resolve();
In ES6+
import path from 'path';
const __dirname = path.resolve();
Happy coding.......
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With