Welcome!

Blog Feed Post

Node.js ABC’s - M is for Modules

npm_logoAs any one who has created a software system can tell you, after some point you get to a point in time where putting all your code in one big location becomes unmanageable and leads to maintenance issues.  The logical first step is to try to separate code that is related into smaller distinct entities and "include" them in the project in question.  But, what happens if two included file "A" and file "B" both define a "doSomething()" method?  Global Scope is sometimes convenient, but more often a cause for troubles when development and enhancing a product.

Different languages handle these "namespace" collisions in different ways.  Some make them optional, some a bit more strict.  Node avoids potential "global scope" issues by not offering an easy way to accidentally over-stuff the global scope.  This is done in the form of "Modules".

At a high level, modules are just an easy way to group similar code together.  Every file in Node.js is considered a module, although modules can be a bit more complex than a single file.  Node modules allow you to select which functions and variables that are in the file are exposed to the calling application and, consequently, which ones are private.

Modules can be packaged and published to an online repository (most likely the Node Package Manager or npm) without those using the modules having to worry about one module conflicting with another in the project.

CREATING MODULES

For the sake of simplicity, we'll focus the following examples on a single file module solution.  To create a new module, just create a new file with the name of your module as it's file name.  Inside that file,  there is a special object calls "exports".  It is with this object, that you specify what you want exposed to the caller.

/* indexGenerator.js */
var counter = 0;
exports.nextIndex = function() {
  return counter++;
}
exports.reset = function() {
  counter = 0;
}

In this example module titled "indexGenerator", I've exposed the following functions:

  • "nextIndex" that will return the next 0-based index in the set.
  • "reset" that will reset the index to 0

That's it, you've created your first module!  The next step is to figure out how to load it and get access to it's functionality.  That is done with the "require" command.  I went into this in detail in my "L is for Loading" article.  I'll point you to that article on the ins and outs of loading a module.

/* test.js */
var generator = require("./indexGenerator.js");
console.log("INDEX: " + generator.nextIndex() + "\n");
console.log("INDEX: " + generator.nextIndex() + "\n");
console.log("resetting index\n");
generator.reset();
console.log("INDEX: " + generator.nextIndex() + "\n");

will produce the following output

INDEX: 0
INDEX: 1
resetting index
INDEX: 0

MODULE PATTERNS

The above example illustrates how to return a set of independent functions from a module.  More often then not, you will want to package your functions into an object and return that to the caller. There are several methods for returning objects from modules: The Factory and The Constructor models

The Factory Model

With the factory module, a creation function is returned in the "exports" object that, when called, will create a new instance of the object in question.  The following code illustrates this:

/* hello.js */
function helloObject() {
  this.sayHi = function() { return "Hi"; }
  this.sayHowdy = function() { return "Howdy"; }
}
exports.createHello = function() {
  return new helloObject();
}
/* test.js */
var helloFactory = require("./hello.js");
var helloObj = helloFactory.createHello();
console.log("HI: " + helloObj.sayHi());

The benefit of this approach is that you can expose many numbers of factories by adding each of them to the exports object along with all other variables and exported standalone functions.

The Constructor Model

Another way to return an object from a module is to override the exports object with the new object in question.  With this approach, you can only return a single item (in this case an object) from your module.

/* hello.js */
function helloObject() {
  this.sayHi = function() { return "Hi"; }
  this.sayHowdy = function() { return "Howdy"; }
}
module.exports = helloObject;
/* test.js */
var helloClass = require("./hello.js");
var helloObject = new helloClass();
console.log("HI: " + helloObj.sayHi());

MODULE FOLDER FORMAT

As I mentioned above, modules can be more than just a file.  You can create a folder structure which contains meta-data, version information, and the module implementation and test files.

/my-module
  /package.json
  /lib
    /module_impl.js
    /file2.js
    ...

package.json
{
  "name": "my-module",
  "version": "1.0.0",
  "main": "./lib/module_impl.js"
}

More information on the Folder Module and the loader rules can be found in my article on Node.js Loading.

PUBLISHING

So you've written a pretty awesome index generator module and you want to share it with the rest of the world.  The Node Package Manager makes it really simple to do so:
- The first step is to thoroughly test out your module.
- Ensure your package.json file has all the info you want to include (help can be found with the "npm help json" command).
- Create an account in the npm registry servers with the "npm adduser" command.
- run "npm publish" from within the module directory.

Pretty simple isn't it!  If you need to manage your package within the repository, you can do so with the "npm unpublish" command.

For more information on Node.js modules, check out the Modules section of the Node.js API reference.

Read the original blog entry...

More Stories By Joe Pruitt

Joe Pruitt is a Principal Strategic Architect at F5 Networks working with Network and Software Architects to allow them to build network intelligence into their applications.

Latest Stories
Interested in leveling up on your Cloud Foundry skills? Join IBM for Cloud Foundry Days on June 7 at Cloud Expo New York at the Javits Center in New York City. Cloud Foundry Days is a free half day educational conference and networking event. Come find out why Cloud Foundry is the industry's fastest-growing and most adopted cloud application platform.
For financial firms, the cloud is going to increasingly become a crucial part of dealing with customers over the next five years and beyond, particularly with the growing use and acceptance of virtual currencies. There are new data storage paradigms on the horizon that will deliver secure solutions for storing and moving sensitive financial data around the world without touching terrestrial networks. In his session at 20th Cloud Expo, Cliff Beek, President of Cloud Constellation Corporation, w...
As enterprise cloud becomes the norm, businesses and government programs must address compounded regulatory compliance related to data privacy and information protection. The most recent, Controlled Unclassified Information and the EU’s GDPR have board level implications and companies still struggle with demonstrating due diligence. Developers and DevOps leaders, as part of the pre-planning process and the associated supply chain, could benefit from updating their code libraries and design by in...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm. In his Day 3 Keynote at 20th Cloud Expo, Chris Brown, a Solutions Marketing Manager at Nutanix, will explore t...
Regardless of what business you’re in, it’s increasingly a software-driven business. Consumers’ rising expectations for connected digital and physical experiences are driving what some are calling the "Customer Experience Challenge.” In his session at @DevOpsSummit at 20th Cloud Expo, Marco Morales, Director of Global Solutions at CollabNet, will discuss how organizations are increasingly adopting a discipline of Value Stream Mapping to ensure that the software they are producing is poised to o...
You know you need the cloud, but you’re hesitant to simply dump everything at Amazon since you know that not all workloads are suitable for cloud. You know that you want the kind of ease of use and scalability that you get with public cloud, but your applications are architected in a way that makes the public cloud a non-starter. You’re looking at private cloud solutions based on hyperconverged infrastructure, but you’re concerned with the limits inherent in those technologies.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
In order to meet the rapidly changing demands of today’s customers, companies are continually forced to redefine their business strategies in order to meet these needs, stay relevant and continue to see profitable growth. IoT deployment and development is integral in this transformation, and today businesses are increasingly seeing the value of investing their resources into IoT deployments. These technologies are able increase ROI through projects such as connecting supply chains or enabling sm...
Cloud applications are seeing a deluge of requests to support the exploding advanced analytics market. “Open analytics” is the emerging strategy to deliver that data through an open data access layer, in the cloud, to be directly consumed by external analytics tools and popular programming languages. An increasing number of data engineers and data scientists use a variety of platforms and advanced analytics languages such as SAS, R, Python and Java, as well as frameworks such as Hadoop and Spark...
IBM helps FinTechs and financial services companies build and monetize cognitive-enabled financial services apps quickly and at scale. Hosted on IBM Bluemix, IBM’s platform builds in customer insights, regulatory compliance analytics and security to help reduce development time and testing. In his session at 20th Cloud Expo, Tom Eck, Industry Platforms CTO at IBM Cloud, will discuss how these tools simplify the time-consuming tasks of selection, mapping and data integration, allowing developers ...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
SYS-CON Events announced today that Outscale, a global pure play Infrastructure as a Service provider and strategic partner of Dassault Systèmes, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Founded in 2010, Outscale simplifies infrastructure complexities and boosts the business agility of its customers. Outscale delivers a secure, reliable and industrial strength solution for its customers, which in...
SYS-CON Events announced today that Progress, a global leader in application development, has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Enterprises today are rapidly adopting the cloud, while continuing to retain business-critical/sensitive data inside the firewall. This is creating two separate data silos – one inside the firewall and the other outside the firewall. Cloud ISVs ofte...
In his session at 20th Cloud Expo, Brad Winett, Senior Technologist for DDN Storage, will present several current, end-user environments that are using object storage at scale for cloud deployments including private cloud and cloud providers. Details on the top considerations of features and functions for selecting object storage will be included. Brad will also touch on recent developments in tiering technologies that deliver single solution and an end-user view of data across files and objects...
SYS-CON Events announced today that Tintri, Inc, a leading provider of enterprise cloud infrastructure, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Tintri offers an enterprise cloud platform built with public cloud-like web services and RESTful APIs. Organizations use Tintri all-flash storage with scale-out and automation as a foundation for their own clouds – to build agile development environments...