Skip to content

Instantly share code, notes, and snippets.

@dotproto
Last active February 14, 2024 01:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotproto/1ac017c0bffcab4538de to your computer and use it in GitHub Desktop.
Save dotproto/1ac017c0bffcab4538de to your computer and use it in GitHub Desktop.
Module-root relative file includes for Node.js
var fs = require('fs');
var path = require('path');
var parentModulePath = path.dirname(module.parent.filename);
// Recursively traverse up a given path tree checking for a file's existence.
function rstat(dir, filename, endPath) {
// End the search at endPath if provided, otherwise default to root
endPath = endPath || path.resolve('/');
var target = path.join(dir, filename);
var stats = null // will contain fstat result
try {
stats = fs.statSync(target);
if (stats.isFile()) {
// Include a filename (the caller won't know otherwise)
stats.file = target;
stats.directory = dir;
stats.filename = filename;
return stats;
}
} catch (e) {}
// Bail if the target dir is the endPath
if (endPath === dir) {
return false;
}
// If we've managed to get here, we didn't match. Try the parent.
return rstat(path.resolve(path.join(dir, '..' )), filename, endPath);
}
function findProjectRoot(){
var stats = rstat(parentModulePath, 'package.json');
if (!stats) {
var err = new Error("Could not find \"package.json\" in the below directory or its parents.\n => " + parentModulePath + "\n");
throw err;
}
return stats.directory;
}
module.exports = function(file) {
var pRoot = findProjectRoot();
return require(path.join(pRoot, file));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment