[node.js] Determine project root from a running node.js application

I've found this works consistently for me, even when the application is invoked from a sub-folder, as it can be with some test frameworks, like Mocha:

process.mainModule.paths[0].split('node_modules')[0].slice(0, -1);

Why it works:

At runtime node creates a registry of the full paths of all loaded files. The modules are loaded first, and thus at the top of this registry. By selecting the first element of the registry and returning the path before the 'node_modules' directory we are able to determine the root of the application.

It's just one line of code, but for simplicity's sake (my sake), I black boxed it into an NPM module:

https://www.npmjs.com/package/node-root.pddivine

Enjoy!