How to create a singleton module in node.js?

Viewed 689

I am trying to create a module which does some work over the network, but also caches recent results to reduce utilization of the resource it accesses. My thought was to just create a module and require it where-ever it is needed. However, in older versions of node this was explicitly said to not work, because require only cached its argument if it resolved to the same path.

With newer versions of node that create a flat structure under node-modules I am thinking that this is no longer true. However, I am still seeing more recent articles on singletons which advocate creating a singleton by a different method:

If you want to create something that behaves like a singleton, you might normally do something like this in your module:

var HelloWorld =
(function () {   
    this.greeting = “Hello, World”;
    return this; 
 })();
module.exports = HelloWorld; 

This would mean that if you load the module multiple times in your application, even in different files, HelloWorld will be invoked only once; and all instances of HelloWorld will point to the same object.

First of all, I don't understand how why this is even true: if you load this module from two different directories, why would HellowWorld be invoked only once? Wouldn't it be invoked once from every different instance of the module that is loaded?

Second of all, is something like this even necessary if using a new enough version of npm that uses a flat installation structure?

0 Answers
Related