Importing and Exporting Modules
In Node.js, modules are a set of functions that can be included in other programs. They help in maintaining a cleaner and more manageable code base. In this tutorial, we will talk about how to import and export modules in Node.js.
What are Node.js Modules?
Node.js has a built-in module system. A module is a JavaScript file that contains a set of functions you want to include in your application.
The primary benefit of using modules is code reusability. You can define your most used functions in a module and import them in your applications, as and when needed. This not only keeps your code clean but also helps manage it better.
How to Export a Module in Node.js?
Let's start by creating a simple module. We will create a new file called greetings.js
and add a function to it.
// greetings.js
function sayHello(name) {
return `Hello, ${name}!`;
}
module.exports = sayHello;
In the code above, sayHello
is a function that takes one argument and returns a string. We are then assigning sayHello
to module.exports
.
The module.exports
or exports
is a special object which is included in every JS file in the Node.js application by default. module
is a variable that represents the current module, and exports
is an object that will be exposed as a module. So, whatever you assign to module.exports
or exports
, will be exposed as a module.
How to Import a Module in Node.js?
Once we have exported a module, we can import it in another file using the require
function. The require
function is used to run and load a JavaScript file and return the exports
object.
Let's create another file called app.js
and import our greetings.js
module.
// app.js
const greet = require('./greetings');
console.log(greet('John Doe')); // Logs: Hello, John Doe!
In the code above, we are importing our greetings.js
module using the require
function and invoking the sayHello
function with an argument.
Exporting Multiple Modules
You can also export multiple modules from a single file by attaching them to the exports
object.
// math.js
exports.add = (x, y) => {
return x + y;
};
exports.subtract = (x, y) => {
return x - y;
};
You can then import these functions in another file.
// app.js
const math = require('./math');
console.log(math.add(5, 3)); // Logs: 8
console.log(math.subtract(7, 2)); // Logs: 5
In the code above, we are importing multiple functions from the math.js
module and invoking them with arguments.
That's it! You now understand how to import and export modules in Node.js. This is a fundamental concept in Node.js and it's important to understand it well because you'll be working with modules a lot when building Node.js applications.