The double underscores in
__dirname looks intimidating but it’s not! It’s a useful variable that’s been around since the beginnging of the NodeJS project. Why’s it such a core feature of Node.js?
__dirname tells you the absolute path of the directory containing the currently executing file.
Here’s a simple example:
gator-app ├──index.js ├──public ├──src │ ├──helpers.js │ └──api │ └──crocodile.js ├──cronjobs │ ├──swamp-pix │ └──get-latest-gators.js └──package.json
console.log(__dirname) // "/Users/Sam/gator-app/src/api" console.log(process.cwd()) // "/Users/Sam/gator-app"
console.log(__dirname) // "/Users/Sam/gator-app/cronjobs" console.log(process.cwd()) // "/Users/Sam/gator-app"
If you noticed,
__dirname has a different value depending on which file you invoked it in, whereas
process.cwd() (another popular Node.js utility) is different. It always returns the same value: the absolute path of where you started the Node.js process (eg.,
$ node index.js).
🐊 Alligator.io recommends ⤵Learn Node, a video course by Wes Bos
When Should I Use It?
__dirname is useful when you want to know the immediate containing folder. You may want to get this path for several reasons:
Making new directories
const fs = require('fs'); const path = require('path'); const dirPath = path.join(__dirname, '/swamp-pix'); fs.mkdirSync(dirPath); // sibling directory was created named "swamp-pix"
Pointing to directories
Adding files to a directory
const fs = require('fs'); const path = require('path'); const filePath = path.join(__dirname, '/swamp-pix/bayou.jpeg'); fs.openSync(filePath, 'a'); // creates file if it doesn't exist
Once you get familiar with Node.js, interacting with your filesystem is easy when you use
__dirname is a global object that’s available to use in all your Node.js modules, without having to import anything. That’s because Node modules get wrapped when executed and given access to a series of global objects.