Search code examples
javascriptnode.jsrequire

Why does this act as a singleton in NodeJS


Why does this act as a singleton in NodeJS, how does it work?

const io = require('socket.io')();

const singleton = module.exports = io;

In essence, if I import this file more than once, I get the first instantiated socket.io instance.


Solution

  • Modules are cached by node. You are returning an instance so whenever you require this file you are getting that same instance (io) each time. The line

    const io = require('socket.io')();
    

    is only ran the first time this module is required. Afterwards, any module that requires this module will only get the returned instance.

    Here is the official documentation on caching: https://nodejs.org/api/modules.html#modules_caching