title: How to create a singleton module in node.js?
body: <p>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 <code>require</code> only cached its argument if it resolved to the same path.</p>
  
  <p>With newer versions of node that create a flat structure under <code>node-modules</code> 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 <a href="https://medium.com/@iaincollins/how-not-to-create-a-singleton-in-node-js-bd7fde5361f5" rel="nofollow noreferrer">different method</a>:</p>
  
  <blockquote>
    <p>If you want to create something that behaves like a singleton, you
    might normally do something like this in your module: </p>
  
  <pre><code>var HelloWorld =
  (function () {   
      this.greeting = “Hello, World”;
      return this; 
   })();
  module.exports = HelloWorld; 
  </code></pre>
    
    <p>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.</p>
  </blockquote>
  
  <p>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?</p>
  
  <p>Second of all, is something like this even necessary if using a new enough version of npm that uses a flat installation structure?</p>