LEARNNode CLI Automation

Node.js Get the Current Working Directory cwd()

There can be a scenario where you would need to acquire the current working directory of your user in your CLI. Fortunately, with the Node.js process object, you can get this directory with a single line of code. Let's take a look at it.

Current Working Directory

You can get the current working directory of your user by using the following line of code in your CLI:

const getWDir = process.cwd()

To explain it further, I am going to execute the Node REPL (Read Evaluate Print Loop) by running the node command in my terminal. And then finally, I am going to run the following command in my terminal:

process.cwd()

This will generate a result like this:

Current Working Directory

You know see in the image that my current working directory has been printed in my terminal.

Wrapping Up

That is how easy it is to use cwd method of the process object to fetch the current working directory. Now you can use this directory path in your CLI and implement something with it. So go ahead and try it out!

Posted by Saad (It's a work in progress: Needs copy editing review by Awais.)