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

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

假设我有以下目录结构:

/ |-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 

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

 Config |-App |-Module |-Command | |-Eat | |-Walk | |-Job |-Breathe 

这按计划运作。

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

是否有一个“直接”的方式来识别实例化的类所在的文件? 我可以访问V8调用堆栈(例如使用堆栈跟踪 )并遍历它:

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; } } } }; 

这是最直接的解决scheme还是您有任何build议或疑虑?

在此先感谢大卫