在nodejs中获取引用脚本文件

时间:2015-05-11 04:22:54

标签: node.js

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

示例:

index.js正在请求helper.js

helper.js中,如何console.log(some_referrer) == '/path/to/index.js')

3 个答案:

答案 0 :(得分:2)

不,这是不可能的。实际上,许多不同的脚本可能需要helper.js,但只会执行一次。只要另一个脚本需要它,它就会返回从第一次module.exports直接包含helper.js时分配给helper.js的内容,而不会再次执行require.main

但是,您可以使用index.js确定运行的原始脚本。这不会告诉您other.js是否需要helper.js需要index.jshelper.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' );


    public void addPolylineBetweenTwoPoint(LatLng point1, LatLng point2, int color) {
        PolylineOptions path = new PolylineOptions()
                .color(color)
                .zIndex(10); // Closes the polyline.

        path.add(point1, point2);

        polyline = map.addPolyline(path);
        // polyline.remove();
    }

答案 1 :(得分:1)

假设所有文件都在同一路径中。

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相同。

答案 2 :(得分:0)

想通了我可以评估require.main === module。当你rtfm发生好事:)

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