0

Here is my issue: I want to use NodeJS's __filename as value of some property. When creating a new instance of that class from another file, the property filename gets __filename value of the file where the class was created, not __filename of the file where I created the instance.

In 'class.js':

class MyClass {
   constructor(props) {
      this.filename = __filename;
   }
}

In 'init.js':

let obj = new MyClass();

Here, obj.filename should be './init.js' but is './class.js'

How can I get __filename to be the filename of the file the instance is created in instead of the file where the class is defined?

Daerendor
  • 128
  • 1
  • 9
  • You have to pass it: `new MyClass(__filename)`. There's no way to access the variable from the scope of your caller. – Bergi Mar 25 '21 at 23:37
  • @Bergi That's sad :'( Thanks – Daerendor Mar 25 '21 at 23:38
  • Yes, it does answer my question! but it is a bit overengineered for my basic use. – Daerendor Mar 25 '21 at 23:58
  • 1
    It's not something i'd typically suggest using. You should rather consider choosing a different design, if somehow possible, that doesn't need this. However, if you really really have no other choice, i guess parsing stack trace as described there might work... – ASDFGerte Mar 26 '21 at 00:02

1 Answers1

0

You can try:

class MyClass {
   constructor(props) {
      this.filename = process.mainModule.filename;
   }
}
Gilson Cavalcanti
  • 1,483
  • 1
  • 12
  • 18
  • `init.js` isn't my main module so this won't work. I have to specify the filename when creating the instance, as @Bergi stated. – Daerendor Mar 25 '21 at 23:53