Search code examples
javascriptnode.jsrequirenode-modules

A possible structure for a Node module


In my node project I'm using this basic template structure for a single module

(function() {

  var SimpleModule;
  SimpleModule = (function() {

    function SimpleModule(params) {

      /** private function */
      this.aPrivateFunction = function() {
        return "hidden";
      };

    }

    /** public function */
    SimpleModule.prototype.foo = function() {
      return "bar";
    }

    return SimpleModule;

  })();

  module.exports = SimpleModule;

}).call(this);

so that the caller module will do

var SimpleModule
 ,simpleModuleInstance;

SimpleModule = require('./simplemodule');
simpleModuleInstance = new SimpleModule();
simpleModuleInstance.foo();

Is this a approach formally correct in Node?


Solution

  • How about a simpler approach? Modules are private by default, so everything's already encapsulated except what you export.

    function SimpleModule(params) {
      /* Not really private!! */
      this.aPrivateFunction = function() {
        return "hidden";
      };
    }
    
    /** public function */
    SimpleModule.prototype.foo = function() {
      return "bar";
    }
    
    module.exports = SimpleModule;