Creating your first Node.js module

Modules are one of the most powerful aspects of Node.js. Organizing your code into modules enforces best-practices. Examples include separation of concerns, code-reuse and test-ability. Publishing a module to the NPM registry is a great way to share your module with others, but we won't discuss that here. In this article, we will create a custom Node.js module for local use. Specifically, we will cover how to reference a local custom Node.js module in package.json. We will also cover how to expose methods from within your custom Node.js module's code. In closing, we will cover how to access the module from a JavaScript file.

To get started, clone the following git hub repository:

https://github.com/kevinchisholm/creating-your-first-node.js-module

(Instructions on how to run the code are available in the Git hub page.)

It all starts with package.json

Sometimes your application depends on functionality that falls outside of Node's core components. In this case, you'll need to import that functionality. This happens in package.json. When creating a custom Node.js module, reference that module's code in package.json.

Example # 1

{
  "name" : "firstNodeJsModuleExample",
  "version" : "0.0.1",
  "dependencies" : {
    "dateTools": "file:my_modules/dateTools"
  }
}

In example # 1, we have the contents of our package.json file. The name and version properties are for demonstration purposes. The dependencies property is more important to us. The dependencies property is an object that contains one or more Node.js modules needed by an application. When running the npm install command, node package manager will download all required modules. The information in the dependencies object tells node package manager what to download.

Specifying a local file instead of a remote resource

In this case, we use a special syntax to import a module that is in the local file system. Notice that the value of the dateTools property is: "file:my_modules/dateTools". This tells node package manager that the dateTools is in the my_modules/dateTools folder.

Our Custom Node Module

Example # 2

var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
    months = ['January', 'February', 'March', 'April', 'May', 'June', 
    'July', 'August', 'September', 'October', 'November', 'December'];

function getDays () {
    return days;
};

function getMonths () {
    return months;
};

function getDay (dayNumber) {
    return (Number.isInteger(dayNumber) && (dayNumber <= (days.length - 1))) ? days[dayNumber] : '';
};

function getMonth (monthNumber) {
    return (Number.isInteger(monthNumber) && (monthNumber <= (months.length - 1))) ? months[monthNumber] : '';
};

// export the module
module.exports = {
    getDays: getDays,
    getMonths: getMonths,
    getDay: getDay,
    getMonth: getMonth
};

In example # 2, we have the contents of our actual module: dateTools. This module does not do too much. In fact, there are four methods: getDays, getMonths, getDay, and getMonth. Notice that there are two arrays: days and months. The getDays and getMonths methods return the appropriate arrays. The getDay, and getMonth methods return the specified day or month, based on the number you pass in as an argument. Again, this module is not one you would probably use in a real-world application. I just added simple methods so that we can have some structure.

File Structure

For this article, what I want to focus on is the architecture of the module. Notice that in the dateTools folder, there are two files: index.js and package.json. You may be thinking: "hmmmm... didn't we already have a package.json file in this application?" Yes, we did. But this is the beauty of Node.js. All modules can in-turn have a package.json file. This way, a module may have its own dependencies. And, those dependencies might each have their own dependencies, and so on. This architecture allows for a highly modular approach to creating software.

Example # 3

{
  "name": "dateTools",
  "description": "Example Node Module",
  "private": true,
  "version": "1.0.0",
  "main": "index.js"
}

In example # 3, we have the package.json file that sits in the root of our custom module. The private property indicates that we do not wish to publish this to the npm registry. The main property indicates the name of the module's JavaScript file. Our module is the result of this file's execution.

module.exports

Every Node.js module has an object named module.exports. This object allows the author to make one or more properties and methods available to the outside world. In our case, we provide an object with properties that correspond to four methods. When any Node.js code references our dateTools module, they are accessing this module.exports object.

The Demonstration Code

Example # 4

// require the dateTools module.
var dateTools = require('dateTools');

//demonstrate the getDay method
console.log('TEST 1: ' + dateTools.getDay(0)); //TEST 1: Monday
console.log('TEST 2: ' + dateTools.getDay(6)); //TEST 2: Sunday

//demonstrate the getMonth method
console.log('TEST 3: ' + dateTools.getMonth(0)); //TEST 3: January
console.log('TEST 4: ' + dateTools.getMonth(11)); //TEST 4: December

//demonstrate the getDays method
console.log('TEST 5: ' + dateTools.getDays()); //TEST 5: All seven days

//demonstrate the getMonths method
console.log('TEST 6: ' + dateTools.getMonths()); //TEST 6: All 12 months

In example # 4, we have the JavaScript file that demonstrates our module. The most important part of the code is line # 2: we use the Node.js require method to import our dateTools module. Notice how we reference the module by name: dateTools. This way, we are not concerned with the actual location of the module. The package.json file in the root of our application takes care of that for us. The name dateTools resolves to: the my_modules/dateTools folder. In that folder, the package.json file resolves the name dateTools to index.js.

Summary

My goal here was to provide an introduction to creating a custom Node.js module. The dateTools module from this article is simple. In fact, it offers little more than four simple methods. This module's purpose was to provide a context for the discussion. I wanted to provide an understanding of how your file organization, and how you access your module. The key to much of this was the file: package.json. This file allows you to keep your code modular and easy to reference. Hopefully, you have found this article helpful and you are on your way to creating your first custom Node.js module.

Author:

Kevin Chisholm blog.kevinchisholm.com

Share This