Why is global object on server side released after some time?


#1

I have a class in one javascript file communicator.js

let communicator = null;
getCommunicator = function () {
  if (!communicator) {
    Log.info("Creating new communicator...");
    communicator = new Communicator();
  }
  return communicator;
};

In order to retrieve the Communicator object I call the getCommunicator()-function in many places in the code to get the same communicator every time, i.e. a singleton.

My intention is thus that, once created, the Communicator object should persist in the global scope forever.

However I have seen that after some inactivity time on my webappliaction, the next time getCommunicator() is called it seems that the reference is gone and it has to create a new.

So any ideas why this is happening? Am I creating the global variable incorrectly? Or does a object has a life time in node?


#2

Are you creating this in a Meteor method? Be careful with let - it’s block-scoped.


#3

Well, yeah its created first time when called in a Meteor method. But if I call the method several times in close time period it is not recreated. So solution would be to change it to var?


#4

You have two issues.

  1. Using let scopes the singleton to the method, and …
  2. A method is associated with each client connection. So, you’ll get a singleton per client.

If you want a true singleton, you could run this as part of the general server code - just put the file in the server/ folder, for example.


#5

I found out what it was.

  • First I already have the file located in the server/folder so thats not it.
  • let, when placed in the global scope is the same as var so thats also no issue.

I was using https://github.com/meteorhacks/cluster so I depending on which worker I was allocated, the Communicator was not allocated for that worker.