'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



Solution 1:[1]

I used something like this and it protects against the error:

let foo = null;
if (typeof window !== "undefined") {
  foo = window.localStorage.getItem("foo");
}

Solution 2:[2]

window object is present only in the context of browser. When running application on nodejs no window object is available. If you want to share your variables or functions across multiple files then you have to use require and exports

client.js

module.exports = {
    fun1: function(){

    },
    counter: 0 
}

and something like in myModule.js

var client = require('./client');

Solution 3:[3]

For node.js the main window objects is called gloabal. Just use it like this:

const example = {
  some: 'Some',
  another: 'Another',
  theOne: function() {
  
    console.log(this.setTimeOut)
    }.bind(global)
 }

Solution 4:[4]

Sometimes, when you are using custom-project, and don't need "window" object at all, just define it with blank, before all other contents:

window = {};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tiago Martins Peres
Solution 2 Arun Redhu
Solution 3 Denise Ignatova
Solution 4 T.Todua