SYS-CON MEDIA Authors: Pat Romanski, Gary Arora, Zakia Bouachraoui, Yeshim Deniz, Liz McMillan

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
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
On-premise or off, you have powerful tools available to maximize the value of your infrastructure and you demand more visibility and operational control. Fortunately, data center management tools keep a vigil on memory contestation, power, thermal consumption, server health, and utilization, allowing better control no matter your cloud's shape. In this session, learn how Intel software tools enable real-time monitoring and precise management to lower operational costs and optimize infrastructure...
"Calligo is a cloud service provider with data privacy at the heart of what we do. We are a typical Infrastructure as a Service cloud provider but it's been designed around data privacy," explained Julian Box, CEO and co-founder of Calligo, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Isomorphic Software is the global leader in high-end, web-based business applications. We develop, market, and support the SmartClient & Smart GWT HTML5/Ajax platform, combining the productivity and performance of traditional desktop software with the simplicity and reach of the open web. With staff in 10 timezones, Isomorphic provides a global network of services related to our technology, with offerings ranging from turnkey application development to SLA-backed enterprise support. Leadin...
While a hybrid cloud can ease that transition, designing and deploy that hybrid cloud still offers challenges for organizations concerned about lack of available cloud skillsets within their organization. Managed service providers offer a unique opportunity to fill those gaps and get organizations of all sizes on a hybrid cloud that meets their comfort level, while delivering enhanced benefits for cost, efficiency, agility, mobility, and elasticity.
DevOps has long focused on reinventing the SDLC (e.g. with CI/CD, ARA, pipeline automation etc.), while reinvention of IT Ops has lagged. However, new approaches like Site Reliability Engineering, Observability, Containerization, Operations Analytics, and ML/AI are driving a resurgence of IT Ops. In this session our expert panel will focus on how these new ideas are [putting the Ops back in DevOps orbringing modern IT Ops to DevOps].
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
Enterprises are striving to become digital businesses for differentiated innovation and customer-centricity. Traditionally, they focused on digitizing processes and paper workflow. To be a disruptor and compete against new players, they need to gain insight into business data and innovate at scale. Cloud and cognitive technologies can help them leverage hidden data in SAP/ERP systems to fuel their businesses to accelerate digital transformation success.
Concerns about security, downtime and latency, budgets, and general unfamiliarity with cloud technologies continue to create hesitation for many organizations that truly need to be developing a cloud strategy. Hybrid cloud solutions are helping to elevate those concerns by enabling the combination or orchestration of two or more platforms, including on-premise infrastructure, private clouds and/or third-party, public cloud services. This gives organizations more comfort to begin their digital tr...
Most organizations are awash today in data and IT systems, yet they're still struggling mightily to use these invaluable assets to meet the rising demand for new digital solutions and customer experiences that drive innovation and growth. What's lacking are potent and effective ways to rapidly combine together on-premises IT and the numerous commercial clouds that the average organization has in place today into effective new business solutions.
Keeping an application running at scale can be a daunting task. When do you need to add more capacity? Larger databases? Additional servers? These questions get harder as the complexity of your application grows. Microservice based architectures and cloud-based dynamic infrastructures are technologies that help you keep your application running with high availability, even during times of extreme scaling. But real cloud success, at scale, requires much more than a basic lift-and-shift migrati...
David Friend is the co-founder and CEO of Wasabi, the hot cloud storage company that delivers fast, low-cost, and reliable cloud storage. Prior to Wasabi, David co-founded Carbonite, one of the world's leading cloud backup companies. A successful tech entrepreneur for more than 30 years, David got his start at ARP Instruments, a manufacturer of synthesizers for rock bands, where he worked with leading musicians of the day like Stevie Wonder, Pete Townsend of The Who, and Led Zeppelin. David has ...
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Addteq is a leader in providing business solutions to Enterprise clients. Addteq has been in the business for more than 10 years. Through the use of DevOps automation, Addteq strives on creating innovative solutions to solve business processes. Clients depend on Addteq to modernize the software delivery process by providing Atlassian solutions, create custom add-ons, conduct training, offer hosting, perform DevOps services, and provide overall support services.