Is there a different way, other than process.cwd(), to get the pathname of the current project's root-directory. Does Node implement something like ruby's property, Rails.root,. I'm looking for something that is constant, and reliable.
33 Answers
There are many ways to approach this, each with their own pros and cons:
require.main.filename
From :
When a file is run directly from Node,
require.mainis set to itsmodule. That means that you can determine whether a file has been run directly by testingrequire.main === moduleBecause
moduleprovides afilenameproperty (normally equivalent to__filename), the entry point of the current application can be obtained by checkingrequire.main.filename.
So if you want the base directory for your app, you can do:
const { dirname } = require('path');
const appDir = dirname(require.main.filename);
Pros & Cons
This will work great most of the time, but if you're running your app with a launcher like pm2 or running mocha tests, this method will fail.