Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - ReferenceError : window is not defined at object. <anonymous> Node.js

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...