Node.js is a JavaScript runtime that is based on Chrome’s V8 JavaScript engine and allows developers to run JavaScript on the server side. Node.js’s ability to use modules, which allows developers to organize and reuse code, is one of its most significant features. In this tutorial, we will look at Nodejs modules and how they may be used to create reusable code.
Creating a Module
A module in Node.js is a standalone piece of code that exports a set of functionality that can be imported and utilized in other sections of your application. Here’s an example of a basic Node.js module:
// myModule.js
exports.sayHello = function() {
console.log("Hello, World!");
}
In this example, we’ll make a module named “myModule” that will export a single function called sayHello. This function only writes a message to the console. To import this module into another area of our program, we may use the need function:
// app.js
var myModule = require('./myModule');
myModule.sayHello(); // logs "Hello, World!"
In this example, we import the “myModule” module by supplying the module file’s path to the need method. The exported functionality may then be accessed by using the object produced by the need method, in this instance myModule.
Exporting Multiple Functionalities
A module can export multiple functionalities, here is an example:
// myModule.js
exports.sayHello = function() {
console.log("Hello, World!");
}
exports.sayGoodbye = function() {
console.log("Goodbye, World!");
}
In this example, we are exporting two methods from the “myModule” module, sayHello and sayGoodbye. Both of these functions may be imported and used in the same way as before.
// app.js
var myModule = require('./myModule');
myModule.sayHello(); // logs "Hello, World!"
myModule.sayGoodbye(); // logs "Goodbye, World!"
Q&A
Q: What is the difference between exports
and module.exports
?
A: exports
is a reference to module.exports
, which is the object that will be returned when a module is imported. exports
is used to add properties and methods to the exported object, while module.exports
is used to replace the exported object entirely.
Q: Can I export an object or a class in a Node.js module?
A: Yes, you can export an object or a class by assigning it to the module.exports
or exports
variable.
We’ve seen how Node.js modules may be used to create reusable code in this post. We’ve gone through how to make a module, export and import functionality from a module, and export an object or a class from a module. We’ve also included activities to help you hone your abilities, as well as answers to the exercises to help you double-check your work. Node.js modules are an useful tool for organizing and structuring your code, making it easier to maintain and develop over time.