Create modules in Node.js
While developing real-world applications using Node.js, we usually need to create our own modules to build a piece of functionality. A module in JavaScript is nothing but a collection of different JavaScript functions and objects that any external application or another module can access. Modules provide a way to reuse code between multiple programs. They also allow us to create more straightforward applications. A module can be beneficial as our program becomes more complex and benefits the team as a whole to collaborate more effectively. Modules help break down code into smaller, reusable pieces that can save time and reduce errors when building more complex applications.
Let’s now check out the steps to create our own modules in Node.js.
Create and consume modules
We’ll follow the steps mentioned below to create our modules and use them in other programs or applications.
Creating a module
In this step, we’ll create our first Node.js module, which will contain a list of greeting messages and one function to get a random greeting message from a set of messages. To implement this, we’ll use the exports
keyword to help export the functionality to other programs or applications. This keyword allows us to make functions and variables available outside the module by attaching them to the exports
object.
Let’s now have a look at the code.
// Creating a class
class Greeting {
constructor(greetingMessage) {
this.greetingMessage = greetingMessage;
}
}
// Creating an array of Greeting objects
const allGreetings = [
new Greeting("Hi, Welcome to Educative :)"),
new Greeting("Welcome back to Educative !"),
new Greeting("Hello"),
new Greeting("Its great to have you here !"),
new Greeting("Greetings of the day!"),
];
// Exporting the function to get a random greeting message
exports.getRandomGreeting = () => {
return allGreetings[Math.floor(Math.random() * allGreetings.length)];
}
// Exporting the array containing all the Greeting objects
exports.allGreetings = allGreetings;
console.log('Module exported!!')
console.log(exports.getRandomGreeting())
Code explanation:
- First, we define a class named
Greeting
containing a constructor to set a greeting message for each class object. - Then, we define an array named
allGreetings
that contains different objects of theGreeting
class. Note that each object has a different greeting message. - We then export an arrow function that returns a random object from the array. Note the usage of the
exports
keyword here. - Finally, we export the
allGreetings
array to be accessible by external programs or applications.
Once we’ve created our module, let’s move on to the next step.
Importing the module
Creating a module is step one, but if we aren’t consuming it, it doesn’t make sense to create a module. Let’s now go over how to import the Greeting
module into a different Node.js file.
// Importing the JavaScript file
const greeting = require('./greeting');
// Printing the objects returned from the Greeting module
console.log(greeting);
Code explanation:
- We import the
greeting.js
file using therequire()
function. - We print the objects to the console that are exported from the module.
- In the output, we can observe that the module successfully exports a function and returns an array of
Greeting
objects.
Access the module
Now let’s try to access the individual property exported by the module.
// Importing the JavaScript file
const greeting = require('./greeting');
// Getting a random greeting message from the Greeting module
const randomMessage = greeting.getRandomGreeting().greetingMessage;
console.log('Random greeting message: ',randomMessage);
// Getting all the greeting messages from the Greeting module
const allGreetingObjects = greeting.allGreetings;
console.log(allGreetingObjects);
Code explanation:
- We call the
getRandomGreeting()
method to get a random message. Since the method returns an object of theGreeting
class, we need to access thegreetingMessage
property of theGreeting
class to get the actual greeting message. - We use the
allGreetings
array and print it to the console. This outputs an array ofGreeting
objects.