在Node JS中,是否可以确定哪个脚本正在请求当前模块?换句话说,谁需要当前脚本?
例子:
index.js
正在要求helper.js
。
在中helper.js
,如何console.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' );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句