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.

Summarize with AI

Not enough time? get the key points instantly.

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.

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.


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

NodeJS

Which Company Is Best for Hiring Node.js Developers in the UK?

Node.js helps businesses build backend systems, REST APIs, real-time applications, and SaaS platforms using JavaScript. Developing these solutions requires professionals who understand application architecture, technical…

NodeJS

How to tell if Node.js is installed or not?

To verify Node.js installation, run node -v or node --version. This checks if Node.js is installed and working correctly. Problem Before you run any Node.js…