在nodejs中引用脚本文件

在节点JS中,是否有可能确定哪个脚本正在请求当前模块? 换句话说,谁需要当前的脚本?

例:

index.js正在请求helper.js

helper.jsconsole.log(some_referrer) == '/path/to/index.js')

不,这是不可能的。 事实上, helper.js可能需要许多不同的脚本,但只能执行一次。 任何时候另一个脚本需要它,它将只返回从第一次分配给module.exports任何helper.js被直接包含,而不再执行helper.js

但是,您可以使用require.main确定运行的原始脚本。 这不会告诉你index.js是否需要other.js所需要的helper.js或者直接需要index.js所需的helper.js 。 但它确实告诉你, index.js是直接执行的原始脚本。

如果你想让helper.js具有不同的行为,取决于它的调用方式,你也可以从helper.js导出一个函数,并期待脚本需要这个函数调用它并传递一个参数:

 // 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' ); 

假设所有文件都在相同的path。

Module1.js

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

Module2.js

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

然后执行。

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

但是,如果你添加

Module3.js

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

然后。

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

所以,基本上,你不能,除非你正在执行的脚本(主脚本)是相同的,这是需要你的Module1。

想通了,我可以评估require.main === module 。 好的事情发生在你rtfm 🙂

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