Writing a Singleton in Node

Singleton Module

Singleton are often needed, here is a quick way to write a singleton in Node.js:

singleton.js

module.exports = {

x: 1,

g: (v) => v*v

}

Use the Singleton

one.js

var singleton = require(‘./singleton’);

module.exports = {

f: () => {

singleton.x = singleton.x + 20;

}

}

two.js

var singleton = require(‘./singleton’);

module.exports = {

f: () => {

singleton.x = singleton.x + 30;

}

}

Test It

test.js

var async = require(‘async’);

var one = require(‘./one’);

var two = require(‘./two’);

var singleton = require(‘./singleton’);

console.log(‘before’, singleton.x);

async.series([

function(callback) {

one.f();

callback(null, ‘one’);

},

function(callback) {

console.log(‘after one’, singleton.x);

two.f();

callback(null, ‘two’);

},

function(callback) {

console.log(‘after one + two’, singleton.x);

one.f();

callback(null, ‘one’);

},

],

function(err, results) {

console.log(‘after one + two + one’, singleton.x);

});

run test:

Run with:

node test.js

Yields:

before 1

after one 21

after one + two 51

after one + two + one 71

Written by

Open source, Mobile, Web, Cloud, Server - Independent Information Technology and Services Professional http://yoramkornatzky.com kornatzky@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store