Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've seen similar questions that were asked here but none matches my situation. In my web I have 3 JavaScript files : client.js , server.js ,myModule.js . In client.js I create a window variable called windowVar and I add to it some atrributes. In myModule.js ,I add some other attributes and use them there and I export the file and require it in server.js.

client.js:

window.windowVar= {
    func1: function(args) {    
       //some sode here
    },
    counter:0
};

myModule.js :

module.exports={wVar:windowVar, addMessage ,getMessages, deleteMessage};

windowVar.serverCounter = 0;
windowVar.arr1=[];

server.js:

var m= require('./myModule');

when running the server in node.js I get the following error:

ReferenceError : window is not defined at object. <anonymous>

As I understood window is a browser property ,but how can I solve the error in this case? Any help is appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
136 views
Welcome To Ask or Share your Answers For Others

1 Answer

window is a browser thing that doesn't exist on Node.

If you really want to create a global, use global instead:

global.windowVar = /*...*/; // BUT PLEASE DON'T DO THIS, keep reading

global is Node's identifier for the global object, like window is on browsers.

But, there's no need to create truly global variables in Node programs. Instead, just create a module global:

var windowVar = /*...*/;

...and since you include it in your exports, other modules can access the object it refers to as necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...