In this tutorial, we will cover the basic concepts of Node.js modules and how to use them in your code with the require
function. Node.js modules are indispensable for structuring your code and making it easier to maintain. By the end of this tutorial, you will be able to create, export, and import modules in Node.js.
Prerequisites: Basic knowledge of JavaScript and Node.js is required.
In Node.js, modules are simply individual JavaScript files that encapsulate related code. This way, you can separate your code into different files, making it easier to maintain and understand.
To create a module, you simply create a new JavaScript file and write your code in it. For instance, let's create a file named greetings.js
.
// greetings.js
let greetings = 'Hello, World!';
function greet() {
console.log(greetings);
}
module.exports = greet;
Here, we've created a function greet
that logs a greeting message to the console. We've then exported this function using module.exports
.
To import a module, you use the require
function. This function is built-in to Node.js and allows you to import modules. Let's see how to import the greeting
module we created earlier.
// app.js
let greet = require('./greetings');
greet(); // Logs: Hello, World!
In app.js
, we import the greeting
module and then call the greet
function. When you run app.js
, you should see Hello, World!
logged to the console.
Let's take a look at more practical examples.
You can export multiple items from a module by attaching them to module.exports
.
// math.js
let pi = 3.14159;
function add(x, y) {
return x + y;
}
function multiply(x, y) {
return x * y;
}
module.exports = {
pi: pi,
add: add,
multiply: multiply
};
Here, we export an object that contains pi
, add
, and multiply
.
When you import a module that exports multiple items, you get an object.
// app.js
let math = require('./math');
console.log(math.pi); // Logs: 3.14159
console.log(math.add(1, 2)); // Logs: 3
console.log(math.multiply(2, 3)); // Logs: 6
In this tutorial, we've learned about Node.js modules and the require
function. Modules allow us to structure our code and require
allows us to import these modules. The key points covered were:
For further learning, consider exploring more complex use-cases of modules and understanding the module loading process in Node.js.
Create a module square.js
that exports a function to calculate the area of a square.
// square.js
function area(side) {
return side * side;
}
module.exports = area;
Create a module circle.js
that exports two functions to calculate the area and circumference of a circle.
// circle.js
let pi = 3.14159;
function area(radius) {
return pi * radius * radius;
}
function circumference(radius) {
return 2 * pi * radius;
}
module.exports = {
area: area,
circumference: circumference
};
For further practice, consider creating modules that interact with external APIs or databases.