3

I'm creating an express 4 project and many of my files are nested within folders. Unfortunately I using a lot of :

var x = require('../../../../file');

I'm thinking I can avoid this if I have access to the base url of the project, but I'm seeing that using a global variable isn't a good idea. What's the best way to tackle this?

Jonathan Eustace
  • 2,469
  • 12
  • 31
  • 54

1 Answers1

3

If you want directory of the root script from which the node process started, you can get it like this:

var root = require.main.filename.slice(0,require.main.filename.lastIndexOf('/'))

or, as @ChiChou suggested:

var root = require('path').dirname(require.main.filename)

This assumes that the main script (or any other script that requires your code) is run from the root directory.

You can use this root as your "base url".

mattr
  • 5,458
  • 2
  • 27
  • 22