Bakyuns Bakyuns - 1 year ago 72
Node.js Question

How can I prevent Node.js from garbage collecting (GC) a critical variable

The property of a variable is purged in Node.js during garbage collection. However, I don't want this to happen. I have found solutions for it, such as saving a variable to a database or file. However, I don't like that approach. I just need a critical section or critical variable protected from garbage collection.

For instance, with the following code:

function a() {
var b;

c = new a();

How can I protect variable
from garbage collection?

After time goes by,
is deleted... In my case,
is deleted...

Please help me... I know my english is very poor, but I need your assistance so much.

Answer Source

One thing to note, in your code b and d are not properties on a. They are local variables to the scope inside of the function a, which are not used, thus get cleaned up.

If you change it to:

function a() {
  this.b = 1;
  this.d = 2;

var c = new a();

console.log(c.b) //1
console.log(c.d) //2

You can then reference c.b and c.d and as long as you have a reference to c, it should not get collected. Also if you have it as var b, d; you cannot reference those from outside of the function.

compare to:

function a() {
  var b = 1;
  var d = 2;

var c = new a();

console.log(c.b) //undefined
console.log(c.d) //undefined
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download