0

Is there a (creative) way to know from which module was a function called ? In order to make the code cleaner and more straightforward.

module-a.js

module.exports = {
    foo = function(calledFrom){
        console.log("foo() called from module: " + calledFrom)
    }
}


// But ideally, something like:
module.exports = {
    foo2 = function(){
        console.log("foo2() called from module: " + arguments[0]) 
        //Or any other way to achieve this generic behaviour
    }
}

module-b.js

require('./module-b.js').foo('module-b')

// But ideally:
require(./module-b.js).foo2()

Coming from python, I like the philosophy of simplicity.

Guilhem Fry
  • 326
  • 4
  • 17
  • this qustion is quite similar - https://stackoverflow.com/questions/33956554/getting-name-of-a-module-in-node-js – Velimir Tchatchevsky Aug 22 '18 at 23:17
  • The info appears to be known to the interpreter (at least at the function and source line number level - not sure about module). See [`console.trace()`](https://nodejs.org/api/console.html#console_console_trace_message_args) for what the interpreter knows in the middle of a function call. I don't know how you could access that info programmatically. – jfriend00 Aug 22 '18 at 23:17
  • @VelimirTchatchevsky This isn't same thing. A module is evaluated only on first import, while a function can be called in multiple places. – Estus Flask Aug 23 '18 at 00:36
  • @estus I was going for using the approach OP has in `func2` and programatically acessing the module name – Velimir Tchatchevsky Aug 23 '18 at 00:47

1 Answers1

0

As explained in this similar answer, caller path can be obtained from stack trace:

const caller = require('caller-callsite');

exports.foo = function(){
    const fullPath = caller().getFileName();
    console.log("foo() called from module: " + fullPath) 
}

A cleaner approach is to specify path explicitly, especially if it's used for something more than just debugging (which is primary objective of stack trace):

require('./module-b.js').foo(__filename)
Estus Flask
  • 206,104
  • 70
  • 425
  • 565