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
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
As you move to the cloud, your network should be efficient, secure, and easy to manage. An enterprise adopting a hybrid or public cloud needs systems and tools that provide: Agility: ability to deliver applications and services faster, even in complex hybrid environments Easier manageability: enable reliable connectivity with complete oversight as the data center network evolves Greater efficiency: eliminate wasted effort while reducing errors and optimize asset utilization Security: imple...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
Transforming cloud-based data into a reportable format can be a very expensive, time-intensive and complex operation. As a SaaS platform with more than 30 million global users, Cornerstone OnDemand’s challenge was to create a scalable solution that would improve the time it took customers to access their user data. Our Real-Time Data Warehouse (RTDW) process vastly reduced data time-to-availability from 24 hours to just 10 minutes. In his session at 21st Cloud Expo, Mark Goldin, Chief Technolo...
The next XaaS is CICDaaS. Why? Because CICD saves developers a huge amount of time. CD is an especially great option for projects that require multiple and frequent contributions to be integrated. But… securing CICD best practices is an emerging, essential, yet little understood practice for DevOps teams and their Cloud Service Providers. The only way to get CICD to work in a highly secure environment takes collaboration, patience and persistence. Building CICD in the cloud requires rigorous ar...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
When it comes to cloud computing, the ability to turn massive amounts of compute cores on and off on demand sounds attractive to IT staff, who need to manage peaks and valleys in user activity. With cloud bursting, the majority of the data can stay on premises while tapping into compute from public cloud providers, reducing risk and minimizing need to move large files. In his session at 18th Cloud Expo, Scott Jeschonek, Director of Product Management at Avere Systems, discussed the IT and busine...
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
Is advanced scheduling in Kubernetes achievable? Yes, however, how do you properly accommodate every real-life scenario that a Kubernetes user might encounter? How do you leverage advanced scheduling techniques to shape and describe each scenario in easy-to-use rules and configurations? In his session at @DevOpsSummit at 21st Cloud Expo, Oleg Chunikhin, CTO at Kublr, will answer these questions and demonstrate techniques for implementing advanced scheduling. For example, using spot instances ...
First generation hyperconverged solutions have taken the data center by storm, rapidly proliferating in pockets everywhere to provide further consolidation of floor space and workloads. These first generation solutions are not without challenges, however. In his session at 21st Cloud Expo, Wes Talbert, a Principal Architect and results-driven enterprise sales leader at NetApp, will discuss how the HCI solution of tomorrow will integrate with the public cloud to deliver a quality hybrid cloud e...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
Companies are harnessing data in ways we once associated with science fiction. Analysts have access to a plethora of visualization and reporting tools, but considering the vast amount of data businesses collect and limitations of CPUs, end users are forced to design their structures and systems with limitations. Until now. As the cloud toolkit to analyze data has evolved, GPUs have stepped in to massively parallel SQL, visualization and machine learning.
DevOps is under attack because developers don’t want to mess with infrastructure. They will happily own their code into production, but want to use platforms instead of raw automation. That’s changing the landscape that we understand as DevOps with both architecture concepts (CloudNative) and process redefinition (SRE). Rob Hirschfeld’s recent work in Kubernetes operations has led to the conclusion that containers and related platforms have changed the way we should be thinking about DevOps and...