Last active
July 20, 2020 12:53
-
-
Save UniDyne/495ee7a3d98f84380d7d19817f06a83e to your computer and use it in GitHub Desktop.
Get the directory of a subclass from the parent class in NodeJS.
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
const path = require('path'); | |
// this is the key function where all the magic happens | |
function getSubclassDir() { | |
// override prepareStackTrace | |
// error.stack will be <CallSite>[] rather than <string> | |
const original = Error.prepareStackTrace; | |
Error.prepareStackTrace = function(err, stack) { return stack; }; | |
// create a new error and use the stack | |
// crawl up the stack until we reach another module | |
// that will be the one that called us - which will be the subclass | |
var err = new Error(); | |
var current = err.stack.shift().getFileName(), callingModule = current; | |
while(err.stack.length > 0 && callingModule == current) | |
callingModule = err.stack.shift().getFileName(); | |
// put original function back | |
Error.prepareStackTrace = original; | |
// return the directory | |
return path.dirname(callingModule); | |
} | |
// superclass sets homeDir - will always be the directory the subclass resides in | |
module.exports = class MySuperClass { | |
constructor() { | |
// check if this is subclass... | |
if(this.constructor.name != 'MySuperClass') | |
this.homeDir = getSubclassDir(); | |
else this.homeDir == __dirname; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment