Determine Project Root From a Running Node JS Application

Use process.cwd() or the app-root-path module to find the project root directory at runtime in Node.js. Useful for loading config files or assets dynamically.

How to Get the Project Root Path in Node.js

When working with large Node.js projects, you often need to find the root directory at runtime for loading config files, managing paths or resolving module imports dynamically. While __dirname gives you the current file’s path, it doesn’t point to the project root.

Method 1: Using process.cwd()

process.cwd() returns the directory where the Node.js process was started. It’s good when your app is launched from the root folder:

js

const rootPath = process.cwd();console.log(rootPath); // e.g., /Users/username/my-app
Note: If you run the script from a subfolder, cwd() will reflect that path.

Method 2: Using app-root-path Module

Install it with:

bash

npm install app-root-path
Usage:

js

const appRoot = require('app-root-path');console.log(appRoot.path);
This will always give you the root path, no matter where the file is located or how the script is executed.
Also Read: How To Update Node JS To Latest Version

Method 3: Using require.main.filename

This will give you the entry point of your application:

js

const path = require('path');const root = path.dirname(require.main.filename); console.log(root);

Conclusion

Use process.cwd() for simple setups, or app-root-path for robust root resolution in complex apps or monorepos.
Related

If you’re trying to run nodemon from the terminal and see the error: nodemon: command not found, it usually means the nodemon package is not…

10 Oct, 2025

Writing to files is a common task in Node.js, whether for logging, saving uploads or creating reports. Node.js has various methods through the built-in fs…

07 Oct, 2025

Startups succeed when they move fast and that requires the right technology. Node.js Developers have become the backbone for agile teams, powering scalable, high-performance apps…

24 Sep, 2025
Request a Quote Schedule a Meeting