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!
Written by Jim Greenleaf
Related protips
2 Responses
This is great! Thank you!
It's awesome to make code clean, but with require we can jump to module but with include, it's not working. any idea how we can do that?
Thanks.