1

In Node JS, Is it possible to determine which script is requesting the current module? In other words, who is requiring the current script?

example:

index.js is requesting helper.js.

In helper.js, how can console.log(some_referrer) == '/path/to/index.js')

3 Answers 3

2

No, it's not possible. In fact helper.js could be required from many different scripts, but will only ever be executed once. Any time another script requires it, it will just return whatever was assigned to module.exports from the first time helper.js was included directly, without executing helper.js again.

You can, however, determine the original script that was run, using require.main. That won't tell you whether index.js required other.js which required helper.js or, index.js required helper.js directly. But it does tell you that index.js was the original script that was executed directly.

If you want helper.js to have different behaviour depending on how it is called, you could also export a function from helper.js and expect the script that requires that function to call it and pass it an argument:

// helper.js
module.exports = function ( arg ) {
    // Use arg to determine which action to take.
};


// index.js
require( 'helper.js' )( 1 );


// other.js
require( 'helper.js' )( 'other' );
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming all files are in the same path.

Module1.js

console.log('required from --> ', require.main.filename);    

Module2.js

var module1 = require('./Module1');

Then exec.

$ node Module2
$ required from -->  /path/Module2.js

But if you add

Module3.js

var module2 = require('./Module2');

Then.

$ node Module3
$ required from -->  /path/Module3.js

So, basically you can't, except if the script you are executing (main script) is the same which is requiring your Module1.

Comments

0

Figured out I can evaluate require.main === module. Good things happen when you rtfm :)

https://nodejs.org/api/modules.html#modules_accessing_the_main_module

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.