Determining your app's base directory in Node.js
Determining your app's base dir (or document root if you're from a PHP background) isn't as straight forward as you'd think in Node. Here's a little trick to get a globally available reference to your app's root directory.
Add this somewhere towards the start of your main app file (e.g.
global.__basedir = __dirname;
This sets a global variable that will always be equivalent to your app's base dir. Use it just like any other variable:
const yourModule = require(__basedir + '/path/to/module.js');
I know what you're thinking: oh no a global! 😫
And I would normally agree, but I think this technique is a fair exception if you're developing an app. Here's why:
- There really isn't a consistent way to references the base dir without it.
- It's a fair requirement to set if you're worried about reusing modules.
- It's a lot easier and more stable than using
../../../file.jsall the time.
- It shares the same naming convention as
There are, of course, other techniques that may or may not be more appropriate depending on your app. However, in my opinion, this approach is the most elegant.