0

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?

qwerty
  • 45
  • 4

1 Answers1

1

You can get the execution path info by error call stack. Here is the example code for 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)
}

But I do think it's better to pass an extra path evaluated in the importer file with __filename or import.meta.url.

John Tribe
  • 1,407
  • 14
  • 26