In Node.js, there are two built-in ways to get the current directory. You can either use the
__dirname variable or the
process.cwd() method to get the current folder. However, there is a big difference between these two options.
On the other hand, the
process.cwd() returns the current working directory from where you started the Node.js application (e.g.
$ node index.js).
Here is a simple example:
node-runner ├──index.js ├──public ├──api │ ├──routes.js │ └──helpers │ └──paths.js ├──mailer │ └──send-email.js └──package.json
Let us say the
paths.js file contains the following code snippet:
Now if you execute the
paths.js from the root directory, you should see the following output:
As you can see above,
__dirname returned the absolute path of the folder where the execution file (
paths.js) resides. Whereas
process.cwd() simply print the current working directory from where the Node.js application was launched.
__dirname variable is extremely useful when you want to get the current containing folder for a file. For example, when creating a new directory inside the current directory, you can use this variable to specify the absolute parent folder path:
const fs = require('fs'); const path = require('path'); // new folder absolute path const dirPath = path.join(__dirname, '/views'); // create directory fs.mkdirSync(dirPath);
Take a look at how to read and write files in Node.js guide to learn more about handling files in a Node.js application.