0

I am currently working with a nodejs project where one of the controller looks following

var express = require('express'),
    router = express.Router(),
    blah = require('blah'),
    Foo = require('../models/foo');


/* Get all foos */

router.get('/', function (req, res) {
    Foo
        .getAll()
        .then(function (foo) {

            return res.json({
                foo: blah(foo)
            });
        })
        .catch(function (err) {
            //handle error;
        });
});

/*
 *  Some other functions
 *
 */

The required module blah and the model Foo are used inside router endpoint. According to this article http://www.ibm.com/developerworks/library/wa-memleak/, I assumed it will not be collected by garbage collector because of it being referenced by a closure inside it and might create a memory leak.

In that case what is the right way of releasing the memory?

1 Answer 1

3

Modules are cached in node.js so they should not leak. They will be loaded once and then any subsequent time they are requested the originally loaded module is returned. So, require() should not be generating a leak. The initial load will take some memory, but subsequent loads should not take more memory. If you call a module constructor or some other module method that uses memory, then that method stands on its own.

In your specific code, the modules blah and Foo are not leaking and are not eligible for garbage collection because they are used in a route handler that is still active and could still be called. They are loaded once and are then available for use by the route handlers if/when they are called. This isn't a leak. This is the desired behavior.

If this isn't exactly what you were asking, then please clarify what you think might be leaking in the above code.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't need to use the Model Foo = require('../models/foo'); after I have done operation with it. So shall I assign it to null after finish working with it?
@MuhammadRaihanMuhaimin - First of all, setting Foo = null won't save you any memory. The module is already in the module cache so doing that won't free anything. Second of all, how can you be "done" with Foo? Your router.get() registers a route handler that can still get hit anytime in the future.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.