Why is __dirname not defined in node REPL?
__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.
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
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