首页 > 解决方案 > 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?

标签: javascriptnode.jstypescript

解决方案


您可以通过错误调用堆栈获取执行路径信息。这是示例代码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)
}

但我确实认为最好在导入器文件中使用__filenameimport.mata.url在构造函数中传递一个额外的路径。


推荐阅读