如何在nodejs中检索调用函数js文件全局变量值

时间:2012-10-30 07:17:55

标签: node.js

来自nodejs的示例代码:

来自JS1.js的代码:

var js2=require("../../util");
var dataName="Billy";
function hello1(){
   js2.hello2("message");
}

来自JS3.js的代码:

var js2=require("../../util");
var dataName="Tom";
function hello3(){
   js2.hello2("message");
}

来自JS2.js的代码:

exports.hello2=hello2;
function hello2(arg1){
   console.log(arg1);
   //Here I need the data in global variable "dataName" of file JS1.js or JS3.js
}

我需要访问调用者js文件的全局变量。

1 个答案:

答案 0 :(得分:1)

所有模块在node.js中共享一个global对象。所以在JS1.js ......

global.dataName = "Billy";

...然后在JS2.js中:

console.log(global.dataName);

但是,以这种方式使用global通常被视为不良形式也就不足为奇了。除非你有一个特殊的理由不希望JS2依赖JS1,否则最好只让JS2导出dataName作为module.exports的一部分。