From the node manual I see that I can get the directory of a file with __dirname
, but from the REPL this seems to be undefined. Is this a misunderstanding on my
In ES6 use:
import path from 'path';
const __dirname = path.resolve();
also available when node is called with --experimental-modules
Seems like you could also do this:
__dirname=fs.realpathSync('.');
of course, dont forget fs=require('fs')
(it's not really global in node scripts exactly, its just defined on the module level)
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
sometimes we make a file with .js extension and add consol.log(_dirname); but we face errors, we are in a hurry, so we forget to add one more underscore before the "dirname" so we face reference error.correct syntax is consol.log(__dirname);
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.......