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. app.js):

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