There are many ways you can get the root directory of a Node.js application, each with its own pros and cons; check out this thread from StackOverflow. In this post, I’ll share with you my preferred way to approach this problem: the path.resolve() method and this is how you can use it:
/** * This will always refer to project's root directory even if called in a nested file */ const rootDir = require('path').resolve('./');
This method works for most use cases and I didn’t encounter any issues with it so far. I hope it’s useful for you too.