How can I get the script name where an object of class is initiated within the class in JavaScript

Viewed 39

I was looking for a way to get all the filenames where my class is imported and initiated an object of the class.

Is it possible to get? If yes, how?

1 Answers

You can log portions of the call stack from the constructor for your class:

Here's an example that works for me:

In test.mjs:

export class Test {
    constructor() {
        let err = new Error();
        console.log(err.stack.split("\n")[1]);
    }
}

In app.mjs:

import { Test } from './test.mjs'

let x = new Test();

When I run app.mjs, it will cause this output:

at new Test (file:///x:/somepath/app.mjs:3:19)

Which is the file, line number and column that created an instance of my class (by calling the constructor).

Related