pavel06081991
pavel06081991

Reputation: 627

How to find out module path in a function

I have such code:

A.js

module.exports = function() {
/*
    Here I need to find out the path of module in which this function was called.
*/
};

B.js

var A = require('./A.js');

A();

C.js

var A = require('./A.js');

A();

Is it possible to find out from which file function of module A is called? I know that I can pass __filename param:

var A = require('./A.js');

A(__filename);

but maybe there is another way without passing any params to A()?

Upvotes: 1

Views: 208

Answers (2)

jfriend00
jfriend00

Reputation: 707328

If I understand your question properly, then the answer is No. A function in Javascript does not know the filename of its caller in any standard way that is documented in a specification. There are some hacks using the exception stack trace, but it is not recommended to use that for a variety of reasons.

You don't explain why you're trying to do this, but in general a function should not change its behavior based on who the caller is. Rather a function should have a defined behavior based on the arguments passed to it. If you want a different behavior when called from B.js and from C.js, then you should specify some argument when calling it in each circumstance that indicates what the behavior should be or create different functions that can be called to generate the different behaviors.

Upvotes: 1

Tobias
Tobias

Reputation: 7771

Well, it is possible, but you really should not do this. You can examine the error stack to get the calling file path like this:

function getCallingFile(n) {
  // Regular expression used to extract the file path
  var exp = / \(([^:]+)(:[^\)]+)?\)$/;
  // Extract line from error stack
  var line = new Error().stack.split('\n')[1 + n];
  // Try to find path in that line
  var m = exp.exec(line);
  if(m) {
    return m[1];
  } else {
    return null;
  }
}

The parameter n means how many levels of the stack should be skipped, in your example it should be 1.

Why shouldn't you do this? Because

  1. the exact format of err.stack has not been specified formally,
  2. this function will fail if you call it from native code,
  3. it is not what error stacks have been designed for and
  4. it enforces a specific directory which might cause problems if you ever refactor your code.

Upvotes: 1

Related Questions