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?

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

var root = require('path').dirname(require.main.filename) may be better.
good suggestion ill add it to the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.