Wednesday, June 05, 2024

Building Node.js Modules, From Concept to Implementation

If you have familiarized yourself with what Node.js is and what it isn't, take a look here; and if you have already installed Node.js on your computer; completed lesson 1; created a small Hello World program. Additionally, if you are using a Linux operating system, such as the Ubuntu distribution, even on a virtual machine, and you have Visual Studio Code installed; then you are definitely ready to learn and code in the JavaScript programming language globally using the Node.js platform. We say globally because not every JavaScript code will work on the Node.js platform. Some things are coded differently. Yes, it is true that you can follow our Node.js tutorial on any operating system; similarly, instead of Visual Studio Code, you can use any IDE - Integrated Development Environment, our recommendation remains Ubuntu and Visual Studio Code.

Of course, the choice is always yours. Unlike various frameworks, when we talk about Node.js, we are talking about a platform, more precisely a multi-platform environment. The Node.js platform allows us to execute JavaScript programming language on the server side or completely outside of the web browser. Node.js has an event-driven architecture capable of performing asynchronous input and output. Which essentially also means that the entire Node.js ecosystem is based on modules through which such events are executed. But what are modules? You can easily understand modules as smaller building blocks of code that divide an application into smaller parts or can even be used in entirely different parts of a program and other programs.

A Programmer Create Node.js Modules

A Programmer Create Node.js Modules

Modules in the Node.js platform mostly contain some functionality coded in the JavaScript programming language, but in such a way that they hide the implementation and provide an explicitly declared API - Application Programming Interface for the module. There are two basic types of modules in Node.js. The first is built-in or Core modules, while the second is non-standard or Custom modules. When it comes to built-in modules, they can also be produced by various other manufacturers. Built-in modules are usually installed into the project you are working on, and the installed module is called a package.

The npm package repository is a vast library of modules available to you to create and develop your Node.js application more easily, better, and faster. As for non-standard modules, you can create and use them in your own project. These modules are user-defined and are not built into Node.js by default. They are used when you want to organize your code into multiple files for better readability and maintenance. However, you can also publish your own packages, which other developers can then use. When Node.js was created, the ES6 module format did not exist, and only the CommonJS module format was used.

Today, both are used. You can recognize the ES6 module format by the *.mjs file extension, although Node.js can be configured to recognize *.js files as ES6 module format. Both types of modules are conceptually similar but differ significantly in practical terms. Working with modules in Node.js is a vast concept that extends throughout the entire Node.js tutorial, and only through practical work with many lessons will you gain a true insight into modules in Node.js. Therefore, consider this lesson just the beginning of the journey through modules in Node.js. It's time to move to the practical level and, through small practical steps, get to know the great possibilities and features that Node.js offers.

From scratch to modules: How to create and run your first Node.js module?

If you are using a Linux operating system, Ubuntu distribution, or another one; first perform an UPDATE and UPGRADE of your system in the terminal. Since it has been quite a long time since we started the first lesson of the Node.js tutorial, check which version of Node.js you have installed on your operating system. In principle, you should always perform the latest Node.js update mainly because of bugs. Then switch to the node_js_tutorial folder and launch Visual Studio Code with the command: 

manuel@manuel-virtual-machine:~/nodejs_tutorial$ code .

When Visual Studio Code is fully opened with the project, type the following command in its panel terminal.

manuel@manuel-virtual-machine:~/nodejs_tutorial$ node lesson1

Server running at http://127.0.0.1:3000/ 

If everything is fine, create a new folder in the main directory and name it lesson2. Then create two new files app.js and lesson2.js in it. Before we start creating modules, first see how to create a package.json file that will contain some basic things about our project but also a list of all packages and their versions that you install in your project, which we call dependencies. Thanks to this *.json file you are able to recover all installed packages in your project in case they are damaged or deleted. We better test it, now! Type the following command in the panel terminal.

manuel@manuel-virtual-machine:~/nodejs_tutorial$ npm init

Then answer a couple of questions.

package name: (nodejs_tutorial) nodejs_tutorial

… Enter

description: node.js tutorial

… Enter

author: Manuel Radovanovic

… Enter

See the package.json file that was created and its contents.

{

  "name""node_js_tutorial",

  "version""1.0.0",

  "description""Node.js Tutorial",

  "main""index.js",

  "scripts": {

    "test""echo \"Error: no test specified\" && exit 1"

  },

  "author""Manuel Radovanovic",

  "license""ISC"

}

And now pay attention. See how packages are installed in your project. For example, we will first install the uuid package. The uuid package provides functionality to generate cryptographically secure standard UUIDs with support for UUID versions 1, 3, 4, and 5, as well as cross-platform support for Node.js, CommonJS, Webpack, React Native Expo, and more.

manuel@manuel-virtual-machine:~/nodejs_tutorial$ npm install uuid

Let's install another package, for example nodemon.

manuel@manuel-virtual-machine:~/nodejs_tutorial$ npm install -D nodemon

Nodemon is a tool that helps in the development of Node.js based applications by automatically restarting the node application when file changes are detected in a directory. In our example today, it doesn't even matter which module packages we install, we only do this so that you can see how the packages are installed. Now look at your project structure. You got a new node_modules folder and a new package-lock.json file. However, look at the contents of the package.json file. The dependencies we installed are added to it.

{

  "name""node_js_tutorial",

  "version""1.0.0",

  "description""Node.js Tutorial",

  "main""index.js",

  "scripts": {

    "test""echo \"Error: no test specified\" && exit 1"

  },

  "author""Manuel Radovanovic",

  "license""ISC",

  "dependencies": {

    "uuid""^9.0.1"

  },

  "devDependencies": {

    "nodemon""^3.0.3"

  }

}

Now imagine that you had some damage to the project. Delete the node_modules folder and the package-lock.json file from your project. Look at the content of the package.json file and you will see that the content of this file has not changed. Thanks to this content, the recovery of our project is simple. Just run the following command in the panel terminal.

manuel@manuel-virtual-machine:~/nodejs_tutorial$ npm install

And our project recovered the lost packages and the package-lock.json file. We hope it is now very clear to you why it is useful to create a package.json file during project creation. Now notice our two new empty files app.js and lesson2.js. Type the following content into the lesson2.js file.

// a variable for the internal use

var count = 0;

// a function which use the variable for the internal use

const next = function() { return ++count; }; 

// a constant for the external use

const PI = 3.14;

// a function for the external use

const sum = (num1, num2) => num1 + num2;

// a class for the external use

class Student {

    // constructor

    constructor(fname, lname, subject) {

        this.fname = fname;

        this.lname = lname;

        this.subject = subject;

    }

    // method

    introduction() {

        console.log(`Hello! My name's ${this.fname} ${this.lname}, and I study ${this.subject}.`); 

    }

}

module.exports.next = next;

module.exports.PI = PI;

module.exports.sum = sum;

module.exports.Student = Student;

In this module, we first wrote how to create a variable count that only has a scope in the specified file, but not outside of it. If you look more carefully at the bottom of the file, you will see that there is no module.exports for the count variable. Module.exports is part of the CommonJS format module specification that defines an object that is created for another file to import and use using the require() function. Then we created a simple function that uses the count variable, but the next() function has its own module.exports and therefore can be called and used in another file. We also created a constant, a function and a class with a constructor and a method and made them all usable by calling the newly created module. To see how it all works, type the following content into the app.js file. 

const lesson2 = require('./lesson2');

console.log(lesson2);

person1 = new lesson2.Student('Manuel''Radovanovic''Computer Science');

console.log(person1);

console.log(person1.introduction());

console.log(lesson2.PI);

console.log(lesson2.sum(5,10));

console.log(lesson2.next());

console.log(lesson2.next());

console.log(lesson2.next());

The first lesson2 constant uses the require() function to literally import the lesson2.js module. It is not necessary to specify the existence of the file, but it is preferable that the modules are in the same directory. Creating and using constants in Node.js is often done because it reduces code printing and avoids typos. Anything defined in a module called with module.exports can be used in a file that calls the module. Type the following command in the terminal panel.

manuel@manuel-virtual-machine:~/nodejs_tutorial$ node lesson2/app

You will get the following result.

{

  sum: [Function: sum],

  PI: 3.14,

  Student: [class Student],

  next: [Function: next]

}

Student {

  fname: 'Manuel',

  lname: 'Radovanovic',

  subject: 'Computer Science'

}

Hello! My name's Manuel Radovanovic, and I study Computer Science.

undefined

3.14

15

1

2

3

As for code optimization; in the lesson2.js file; comment out the following piece of code:

/*

module.exports.next = next;

module.exports.PI = PI;

module.exports.sum = sum;

module.exports.Student = Student;

*/

You can also write this in this abbreviated way.

module.exports = { sum:sum, PI:PI, Student:Student, next:next }

You can see how we created all this and how it all looks in the following video.

Node.js - 1. How to create and run a Node.js module? 









No comments:

Post a Comment