Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
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; = 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;
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