SYS-CON MEDIA Authors: Yeshim Deniz, Pat Romanski, Elizabeth White, Liz McMillan, William Schmarzo

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
For far too long technology teams have lived in siloes. Not only physical siloes, but cultural siloes pushed by competing objectives. This includes informational siloes where business users require one set of data and tech teams require different data. DevOps intends to bridge these gaps to make tech driven operations more aligned and efficient.
NanoVMs is the only production ready unikernel infrastructure solution on the market today. Unikernels prevent server intrusions by isolating applications to one virtual machine with no users, no shells and no way to run other programs on them. Unikernels run faster and are lighter than even docker containers.
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO Silicon Valley 2019 will cover all of these tools, with the most comprehensive program and with 222 rockstar speakers throughout our industry presenting 22 Keynotes and General Sessions, 250 Breakout Sessions along 10 Tracks, as well as our signature Power Panels. Our Expo Floor will bring together the leading global 200 companies throughout the world of Cloud Computing, DevOps, IoT, Smart Cities, FinTech, Digital Transformation, and all they entail. As ...
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...
Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throughout enterprises of all sizes. We are offering early bird savings...
SUSE is a German-based, multinational, open-source software company that develops and sells Linux products to business customers. Founded in 1992, it was the first company to market Linux for the enterprise. Founded in 1992, SUSE is the world’s first provider of an Enterprise Linux distribution. Today, thousands of businesses worldwide rely on SUSE for their mission-critical computing and IT management needs.
The dream is universal: heuristic driven, global business operations without interruption so that nobody has to wake up at 4am to solve a problem. Building upon Nutanix Acropolis software defined storage, virtualization, and networking platform, Mark will demonstrate business lifecycle automation with freedom of choice and consumption models. Hybrid cloud applications and operations are controllable by the Nutanix Prism control plane with Calm automation, which can weave together the following: ...
Crosscode Panoptics Automated Enterprise Architecture Software. Application Discovery and Dependency Mapping. Automatically generate a powerful enterprise-wide map of your organization's IT assets down to the code level. Enterprise Impact Assessment. Automatically analyze the impact, to every asset in the enterprise down to the code level. Automated IT Governance Software. Create rules and alerts based on code level insights, including security issues, to automate governance. Enterpr...
Your job is mostly boring. Many of the IT operations tasks you perform on a day-to-day basis are repetitive and dull. Utilizing automation can improve your work life, automating away the drudgery and embracing the passion for technology that got you started in the first place. In this presentation, I'll talk about what automation is, and how to approach implementing it in the context of IT Operations. Ned will discuss keys to success in the long term and include practical real-world examples. Ge...
Cloud is the motor for innovation and digital transformation. CIOs will run 25% of total application workloads in the cloud by the end of 2018, based on recent Morgan Stanley report. Having the right enterprise cloud strategy in place, often in a multi cloud environment, also helps companies become a more intelligent business. Companies that master this path have something in common: they create a culture of continuous innovation.
Eric Taylor, a former hacker, reveals what he's learned about cybersecurity. Taylor's life as a hacker began when he was just 12 years old and playing video games at home. Russian hackers are notorious for their hacking skills, but one American says he hacked a Russian cyber gang at just 15 years old. The government eventually caught up with Taylor and he pleaded guilty to posting the personal information on the internet, among other charges. Eric Taylor, who went by the nickname Cosmo...
DevOpsSUMMIT at CloudEXPO, to be held June 25-26, 2019 at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Am...
The benefits of automated cloud deployments for speed, reliability and security are undeniable. The cornerstone of this approach, immutable deployment, promotes the idea of continuously rolling safe, stable images instead of trying to keep up with managing a fixed pool of virtual or physical machines. In this talk, we'll explore the immutable infrastructure pattern and how to use continuous deployment and continuous integration (CI/CD) process to build and manage server images for any platfo...
Automation is turning manual or repetitive IT tasks into a thing of the past-including in the datacenter. Nutanix not only provides a world-class user interface, but also a comprehensive set of APIs to allow the automation of provisioning, data collection, and other tasks. In this session, you'll explore Nutanix APIs-from provisioning to other Day 0, Day 1 operations. Come learn about how you can easily leverage Nutanix APIs for orchestration and automation of infrastructure, VMs, networking, an...
It cannot be overseen or regulated by any one administrator, like a government or bank. Currently, there is no government regulation on them which also means there is no government safeguards over them. Although many are looking at Bitcoin to put money into, it would be wise to proceed with caution. Regular central banks are watching it and deciding whether or not to make them illegal (Criminalize them) and therefore make them worthless and eliminate them as competition. ICOs (Initial Coin Offer...