Seyi Adekoya
Seyi Adekoya

Reputation: 453

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.

Upvotes: 0

Views: 180

Answers (1)

adam-beck
adam-beck

Reputation: 6009

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

Upvotes: 3

Related Questions