Last active
February 14, 2024 01:55
-
-
Save dotproto/1ac017c0bffcab4538de to your computer and use it in GitHub Desktop.
Module-root relative file includes for Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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