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
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.