Log In

How to Create a Node.js Module

How to Create a Node.js Module
26.01.2024
Reading time: 7 min
Hostman Team
Technical writer

Node.js modules provide a way to create loosely coupled programs that scale with the increasing complexity of a project. Creating modules can benefit the Node.js community and improve the programmer's skills.

Node.js modules can be of different types, such as:

  • database modules: mongodb, mysql, sequelize (for ORM support);

  • network modules: net (for working with TCP and UDP sockets), dns (for working with domain name system), request (library for HTTP requests);

  • modules for developing web applications: ejs (template engine), socket.io (library for working with web sockets), passport (library for authentication and authorization of users).

Also, Node.js has built-in and third-party modules. Some examples of built-in extensions are fs (file handling), http (HTTP protocol handling), crypto (cryptographic functions), and path (path handling). Modules developed by third-party developers can be installed using the NPM package manager.

In this article, we will look at creating a third-party module to help designers choose colors for their projects, and learn how to import it. After that, you can easily create any Node.js module and perform various operations.

Preparation

Before creating a Node.js module, install the platform itself along with NPM. Node Package Manager allows you to manage dependencies and install packages. It also contains many pre-built packages and provides a convenient way to install, upgrade, and uninstall them. In addition, NPM allows you to create and publish your own packages for other developers to use.

Installing Node.js with Node Package Manager is easy. Let's look at it separately for Linux / macOS and Windows.

  • To install Node.js and NPM on Linux and macOS:

Open a terminal and run the following command under the root user or use sudo:

apt-get update
apt-get install nodejs

Now install NPM by running the command:

apt-get install npm

Check the platform and manager versions by running the commands:

node -v
npm -v
  • To install Node.js and NPM on Windows:

Download the Node.js installation file from the official website and run it. Install the platform along with the package manager by following the installer instructions. After installation, check the versions of Node.js and NPM. To do this, open a command prompt (press Win+R and type cmd) and run the commands:

node -v
npm -v

If the terminal displays the programs’ versions, the installation was successful. Now you can start developing your first module.

Creating the module

Open the terminal, create a directory, and navigate there:

mkdir colors
cd colors

Now initialize the Node Package Manager to allow import:

npm init -y

The -y flag is used to skip unnecessary dialogs when configuring package.json. The command will create a package.json file with information about the name, the main file, scripts and errors in them, as well as several other parameters (description, version, keywords, author, license, etc.):

Image1 (1)

Now open nano or another editor and create a new file. This file is needed to create an entry point.

nano index.js

It will create an index.js file in the ~/colors/ directory.

Now, define a class. It should have a name as well as a code. Write:

class Color {
  constructor(name, code) {
    this.name = name;
    this.code = code;
  }
}

Next, write the colors to the file. For example, we'll use several shades of red:

const allColors = [
  new Color('IndianRed', '#CD5C5C'),
  new Color('LightCoral', '#F08080'),
  new Color('Salmon', '#FA8072'),
  new Color('Crimson', '#DC143C'),
  new Color('FireBrick', '#B22222'),
  new Color('DarkRed', '#8B0000'),
];

Now, create a function designed for random selection:

exports.getRandomColor = () => {
  return allColors[Math.floor(Math.random() * allColors.length)];
}
exports.allColors = allColors;

Everything stored in the exports key will be exposed on import. Now save and close the file (in nano, you need to press Ctrl+X and then Y to save the changes) and proceed to the next step.

Testing the module

For this, we will need some skills with one of the tools: REPL. REPL is an interactive environment that allows the user to enter commands in a specific programming language, which are then immediately executed and displayed on the screen. This way, REPL allows you to test and debug code step-by-step without creating entire programs or scripts. The user can enter commands one by one and immediately see the result of their execution, which makes the development process faster and more efficient. REPL is used to develop programs in JavaScript and many other languages, including Python, Ruby, Lisp, etc.

So, first, start REPL with a simple command:

node

Now enter the following in the REPL interface (here, we also use the native language of the platform, JS):

colors = require('./index');

Press Enter to display a list of our colors with their hex codes. This is what you will see:

Image3 (1)

Now proceed to the actual testing by typing:

colors.getRandomColor();

The program should output a random color. To be sure, try typing this command a few more times. At this point, the testing is successfully completed, but remember to exit the REPL with the following command:

.exit

Saving the local module as a dependency

This step is necessary to ensure that the modules work regardless of conditions (for example, when the project directory changes). To do this, create a new module. Locate it in some other directory outside of your project and navigate there:

mkdir other_nodejs_project
cd other_nodejs_project

Next, initialize the new module using the Node Package Manager:

npm init -y

NPM will generate a new package.json. Next, install our module there like this:

npm install --save ../colors

Open the file with nano:

nano package.json

We should see the dependency lines added:

Image2 (1)

Close the file and check the location of our main module, like this:

ls node_modules

The output should show the name of our module. 

Next, type:

nano index.js

Add the following lines to check if it works correctly:

const colors = require('colors');
const chosenColor = colors.getRandomColor();
console.log(`Please use the ${chosenColor.name} color on your site. Its HTML code is ${chosenColor.code}`);

This directive in the new index.js will allow you to import the working colors module and select a random shade.

Now save the changes, close the file, and run the script:

node index.js.

In response, you will get a random color with a recommendation and hex code:

Please use the FireBrick color on your site. Its HTML code is #B22222

To make sure that the program offers random colors, run it a few more times. You can add any number of new colors; just don't forget to update the module with the command:

npm update

And now, we are moving on to the final step.

Linking the local module

We need to do this to ensure that packages containing our module will update when changes to the module are made. During the development process, the programmer is constantly making changes to the code, and it is extremely inconvenient to manually update all the dependencies the package uses. That's why, first of all, we delete the local module with the command:

npm un colors

Now add a global reference as follows:

cd ../colors
sudo npm link

Next, go back to the other_nodejs_project directory:

cd ../other_nodejs_project
sudo npm link colors

That's it; we've linked the local module, so let's check how it works:

node index.js

The result will be a random value with a comment, like in the example above:

Please use the FireBrick color on your site. Its HTML code is #B22222

There's not much left to do. Check if the updates are applied:

cd ../colors
nano index.js

And add this directive at the end of the file (instead of green, you can add any other color):

exports.getGreen = () => {
 return allColors[2];
}

Save and close the file. 

Now edit the file in the other directory:

cd ../other_nodejs_project
nano index.js

Add at the bottom:

const favoriteColor = colors.getGreen();
console.log(`By the way, my favorite color is ${favoriteColor.name}/${favoriteColor.code}`);

Once again, save and close the file and run it to test it:

node index.js

The output should be something like this:

Please use the FireBrick color on your site. Its HTML code is #B22222
By the way, my favorite color is green/#008000

As you can see, we didn't have to update the module via NPM. We should add that this method of updating is suitable when developers are actively working with the code, constantly changing it. Otherwise, it is enough to use the npm install command to install the module.

Conclusion

So, we have learned how to create and test modules, make them work independently, and link them to make it easier to update applications that use our modules. Good luck with creating new modules!


Share