I have an application with directories, and files in those directories reference each other via require
. I may move them around, so I hate to use relative paths. Is there a way to use paths relative to my application root?
I have
/home/robert/src/application/
|\ routes
| \ foo.js
|\ models
\ bar.js
// foo.js
var bar = require('../models/bar')
, stuff = require('../other_stuff/stuff');
I want
/home/robert/src/application/
|\ routes
| \ foo.js
|\ models
\ bar.js
// foo.js
var bar = require('/models/bar')
, stuff = require('/other_stuff/stuff');
except that the paths are appended to /home/robert/src
instead of evaluated on their own.
A lot of people have started creating an index.js
file that exports all of their modules from a single place. Modules then just require these exports from the index file instead of where the modules are actually defined. If you ever move anything around, you just need to update this one file. Plus it makes creating code coverage builds much easier.
Index.js just ends up with a bunch of lines like this:
module.exports.app = process.env.EXPRESS_COV ?
require('./lib-cov/app') : require('./lib/app');
Basically this exports app
for any module that needs it using either the standard module or the code coverage version depending on a variable.
What about
require(__dirname + '/models/bar');
See: http://nodejs.org/docs/latest/api/globals.html#globals_dirname
Put your application into one folder in the app root (say, ./app
), then include this snippet into your package.json
:
"scripts": {
"postinstall": "ln -sf ../app ./node_modules"
}
And run the command. This will soft-link the app
folder into your node_modules
, allowing Node and require
to do what it does best. You'll be able to require your modules like so:
require('app/routes/foo')
(Windows users will need to do it manually; not sure if it would work on Windows at all.)