Skip to content

ReferenceError : window is not defined at object. 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

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.