Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does NodeJS reuse already loaded modules and share it's values?

I'm starting to build my project in NodeJS and was wondering

  • Does NodeJS reuse already loaded modules for modules requiring the same module?
  • Do the modules keep the same "state" across modules that require them?
  • What's the catch if either or both happen? Am staring in the face an issue similar to loops and setTimeout and async code?

Currently I have tested with 4 files

  • common.js

    var i = 0;
    
    function add(v){i += v;}
    function view(){console.log(i);}
    
    module.exports = {
        add : add,
        view : view
    }
    
  • a.js and b.js

    exports.common = require('./common.js');
    
  • server.js

    var a = require('./a.js'),
        b = require('./b.js');
    
    function start(){
        http.createServer(function (req, res) {
    
            a.common.add(2);
            a.common.view();
    
            b.common.add(4);
            b.common.view();
    
            a.common.view();
    
    
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end('Hello World\n');
        }).listen(config.port, config.address || '127.0.0.1');
        console.log('Server running');
    }
    

The result gives me a suggestive result that it does:

2  - view() via a.js on favicon request
6  - view() via b.js on favicon request
6  - view() via a.js on favicon request
8  - view() via a.js
12 - view() via b.js
12 - view() via a.js

It seems that it does seem to share the module even if it is required by two separate modules, and even keeps state across modules and across requests

like image 382
Joseph Avatar asked Aug 21 '12 11:08

Joseph


2 Answers

Node.js caches modules for obvious performance reasons.

Statement from the Node.js website:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles. If you want to have a module execute code multiple times, then export a function, and call that function.

like image 181
jamjam Avatar answered Nov 03 '22 22:11

jamjam


Yes, all modules are cached after the first time they are loaded. You can read more about module caching in official node.js docs.

like image 24
Vadim Baryshev Avatar answered Nov 03 '22 23:11

Vadim Baryshev