Sample Code from nodejs:
Code from JS1.js :
var js2=require("../../util");
var dataName="Billy";
function hello1(){
js2.hello2("message");
}
Code from JS3.js :
var js2=require("../../util");
var dataName="Tom";
function hello3(){
js2.hello2("message");
}
Code from 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
}
I need to access the global variable of caller js file.
All modules share a global
object in node.js. So in JS1.js ...
global.dataName = "Billy";
... then in JS2.js:
console.log(global.dataName);
However, it shouldn't be surprising that using global
in this way is generally considered poor form. Unless you have a specific reason for not wanting JS2 to depend on JS1, it's probably better to just have JS2 export dataName
as part of it's module.exports
.