How to make node.js require absolute? (instead of relative)

I would like to require my files always by the root of my project and not relative to the current module.

For example if you look at https://github.com/visionmedia/express/blob/2820f2227de0229c5d7f28009aa432f9f3a7b5f9/examples/downloads/app.js line 6 you will see

express = require('../../')

That’s really bad IMO. Imagine I would like to put all my examples closer to the root only by one level. That would be impossible, because I would have to update more than 30 examples and many times within each example. To this:

express = require('../')

My solution would be to have a special case for root based: if a string starts with an $ then it’s relative to the root folder of the project.

Any help is appreciated, thanks

Update 2

Now I’m using require.js which allows you to write in one way and works both on client and on server. Require.js also allows you to create custom paths.

Update 3

Now I moved to webpack + gulp and I use enhanced-require to handle modules on the server side. See here the rationale: http://hackhat.com/p/110/module-loader-webpack-vs-requirejs-vs-browserify/

38 Answers
38

And what about:

var myModule = require.main.require('./path/to/module');

It requires the file as if it were required from the main js file, so it works pretty well as long as your main js file is at the root of your project… and that’s something I appreciate.

Leave a Comment