Does express.js have the concept of a home directory?

Problem

I have an express project where I have a directory structure like so,

  • my-app
    • routes
      • index.js
    • views
    • public
    • components
      • toolbar
    • test
      • components
      • toolbar

Now let's say from my routes I want to require the component toolbar I do it like this

toolbar = require(__dirname + '/../components/toolbar')

Now when I run my test for routes I need to require routes. When I do this I get an error at runtime that toolbar file could not be found.

Is there some global available like say __express_home that I could use in my require so that I would not run into this issue? I would then use it as so,

toolbar = require(__express_home + '/components/toolbar')

Problem courtesy of: Moiz Raja

Solution

You can just do:

toolbar = require('../components/toolbar')

Here is an example from express's github repo.

var express = require('../..')
  , app = express()
  , site = require('./site')
  , post = require('./post')
  , user = require('./user');
Solution courtesy of: 3on

Discussion

just use a relative path from wherever you are require() it.

./routes/index.js ./config.js

from ./routes/index.js

var cfg = require('../config');
Discussion courtesy of: chovy

This recipe can be found in it's original form on Stack Over Flow.