When you develop a NodeJS application, you probably get to work with services and as much as possible with service dependency injection.
As I worked quite a lot with Symfony lately, I wanted to be able to manage my NodeJS services as it should be, and in some case, like a database connection: a single instance for the whole script.

I quicky looked onto Internet to see how to build a singleton in JavaScript (pardon my weak skills in this language) and I quickly found what I was (almost) looking for.

Code examples provided in the different posts I've read would not show what I really needed: a JavaScript module that acts as a singleton.

So after tweaking a little, here's a very basic example of a JavaScript module that acts as a singleton:

// singleton.js
module.exports = (function() {
    // Singleton instance goes into this variable
    var instance;

    // Singleton factory method
    function factory() {
        return Math.random();

    // Singleton instance getter
    function getInstance() {
        // If the instance does not exists, creates it
        if (instance === undefined) {
            instance = factory();

        return instance;

    // Public API definition
    return {
        getInstance: getInstance

And now, from the caller script:

// test.js
var singleton = require('./singleton');


Execute the code:

$ node test.js

How easy right? I'm so glad to learn new little things everyday :)

If you are a JavaScript skilled engineer and have a feedback about this, I'd love to read it.


Joris Berthelot