node.js - 获取超类中 ES6 子类的文件名

dav*_*dev 6 inheritance filenames module class node.js

我目前正在开发一个 node.js (v5.10.1) 应用程序,该应用程序使用 ES6 类语法进行模块公开,尽管我不确定这是否与我面临的问题特别相关。

假设我有以下目录结构:

/
|-command/
| |-walk/
| | |-config.json
| | |-walk.js
| |
| |-eat/
|   |-config.json
|   |-eat.js
|
|-core/
| |-app.js
| |-command.js
| |-config.json
| |-config.js
| |-job.js
| |-module.js
|
|-job/
| |-breathe/
|   |-config.json
|   |-breathe.js
|
|-init.js
Run Code Online (Sandbox Code Playgroud)

位于每个.js文件中的类遵循以下继承:

Config
|-App
|-Module
  |-Command
  | |-Eat
  | |-Walk
  | 
  |-Job
    |-Breathe
Run Code Online (Sandbox Code Playgroud)

这按计划工作。

现在是关键部分:在我的Config类中,我想实现一个可供所有子类和子子类(等等)类使用的方法,并访问它们的各个目录(例如/command/eat/forEat/core/for App)以加载相关config.json文件,其中包含默认配置。

是否有一种“直接”的方式来识别实例化类所在的文件?我可以访问 v8 调用堆栈(例如使用stack-trace)并对其进行迭代:

config.js

const path = require('path');
const stackTrace = require('stack-trace');
module.exports = class Config {
    constructor() {
        for (var callSite of stackTrace.get()) {
            if (callSite.getFunctionName() === this.constructor.name) {
                console.log(path.dirname(callSite.getFileName()));
                break;
            }
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

这是最直接的解决方案还是您有任何建议或疑虑?

提前致谢,大卫