javascript - Get class initiation location path in Node js
问题描述
I have a class in a file:
// file: MyClass.js
class MyClass {
constructor() {
...
}
...
};
export default MyClass;
And in another file (in another directory):
// file: SomeFile.js
import MyClass from <file_path>;
const instance = MyClass();
I want to get the location of the instance initiation, and I would like to get it in the class itself.. maybe something like that:
// file: MyClass.js
class MyClass {
constructor() {
this.instPath = getInstPath(); // => string of the SomeFile.js path
...
}
...
};
export default MyClass;
I want to get this string path without passing any parameters in the class instance, any ideas?
解决方案
您可以通过错误调用堆栈获取执行路径信息。这是示例代码getInstPath
:
import url from 'url'
function getInstPath() {
const stack = new Error().stack;
// The 1st line is `Error`
// The 2nd line is the frame in function `getInstPath`
// The 3rd line is the frame in `MyClass` calling `getInstPath`
// So the 4th line is the frame where you instantiate `MyClass`
const frame = stack.split('\n')[3];
const fileUrlRegExp = /(file:\/\/.*):\d+:\d+/g;
const fileUrl = fileUrlRegExp.exec(frame)[1];
return url.fileURLToPath(fileUrl)
}
但我确实认为最好在导入器文件中使用__filename
或import.mata.url
在构造函数中传递一个额外的路径。
推荐阅读
- javascript - 在Javascript中将对象作为参数传递时的奇怪行为
- bash - ffmpeg 启动时间太长
- matlab - Matlab - 具有不同系数的多项式根
- json - 使用 JMESPath 和/或 Ansible 组合 JSON 项
- c# - csla 4.5.600 -> csla 5.3.1 迁移大问题
- java - 如何为每个回收站项目制作不同的资源 ID?
- javascript - 页面在 NextJS 生产中短暂没有样式?
- r - R Predict 产生的值不同于手动计算
- javascript - 如何在 JavaScript 中构建 Spring 表单
- java - RazorPay 与 React JS 和 Java 应用程序集成