th6ssq
Last Updated: February 25, 2016
·
11.51K
· amoniker
Avatar closeup

Absolute paths & require()

A quick one:

Normally, when referencing a file with require() a relative path is used. This path must reflect the position of the current file within your site's directory structure.

However, I'd rather use an absolute path based only on my site's top-level directory, and not on whichever file I'm currently in.

So, I include this snippet at the top of my main.js:

global.base_dir = __dirname;
global.abs_path = function(path) {
  return base_dir + path;
}
global.include = function(file) {
  return require(abs_path('/' + file));
}

Now when you're in a file, instead of writing something like this:

require('../../../lib/Utils.js');

You can write this:

include('lib/Utils.js');

Not only is this more readable, you also don't have to remember where in the file hierarchy you are when you'd like to include something.

Another benefit is that you won't have to update any paths if you move a file containing an include().

Lastly, when you need to get the full path to a file (perhaps for use with the fs module) you can use the global function:

abs_path('lib/Utils.js');

Cheers!

Say Thanks
Respond

1 Response
Add your response

12279
89014c7d6e68d21f0d872e8dca9778f6

This is great! Thank you!

over 1 year ago ·