Search code examples
node.jsmemorymoduleexpressconflict

How to avoid memory conflicts on ExpressJS/Node.js


I'm using Express and Passport for node.js to build a simple web server, I coded a simple module and then I loaded the module inside a GET request, everything works great until more than one user access the request.

I use to believe that a "var" inside an "app.get" function was removed from memory after the function finished, but isn't the case, I use some local variables inside the external module and the values are being shared between users, the module looks like this:

var some_value=0;
function some_method(){
    some_value++;
    return some_value;
}
exports.some_method = some_method;

And the Express request code looks like this:

app.get('/someurl', function(req, res) {
    var some_extermal_module = require('/some_extermal_module'); // <-----Right way?
    var data = some_extermal_module.some_method();
    res.render('view', {
        title : 'Title',
        data_to_vew: data
    });
});

An object inside a "app.get" request stays always in memory regardless of is being accessed by a different user?

How to clean a "var" object after it runs?

How can I avoid this memory conflicts?

Do I have to code differently the module or call differently the module?

Thanks a lot.

UPDATE: I guess this is a proper solution but I need the review of some node.js/Express expert for approval it or correction.

app.js:

var ext_mod = require('./module');

var express = require('express');
var app = express();

app.get('/', function(req, res){
    var ex_mod_instance = new ext_mod({});
    ex_mod_instance.func_a({},function(ret){
        res.send('Hello World: '+ret);
    });
    ex_mod_instance = null; // clean
});

app.listen(8080);
console.log('Listening on port 8080');

module.js:

var node_module = function(config) {
    this.config = config;
    this.counter=0;
};

node_module.prototype = {
    func_a: function(param,done) {
        this.counter++;
        done(this.counter);
    },
    func_b: function(param,done) {
    }
};

module.exports = node_module;

Is this the best way to save memory (leaks)?


Solution

  • Every time a function is called you do get "clean" local variables in the local scope. Modules are for the purpose of writing clean, organized code, so that you do not have every function and variable in the global scope. I believe require does cache the module, so maybe you are having a problem with variables in the closure around the function exported from the module. You'll have to include more code.

    One way you could solve this is by exporting a function that creates the module. That function could be your constructor, which will scope your counter locally.

    Again, this is one solution.