This tutorial will guide you through the process of creating and exporting your custom modules in Node.js.
By the end of this tutorial, you will be able to:
1. Create your own custom modules in Node.js.
2. Export your custom modules for use in other parts of your application.
Basic knowledge of JavaScript and Node.js is necessary. Familiarity with ES6 syntax will be beneficial but not mandatory.
Modules in Node.js are standalone JavaScript files that export functionalities to be used in other files. They help in organizing code into separate parts with a well-defined interface.
To create a module, we simply create a new JavaScript file and write our module code into it.
To make the functionalities available to other files, we use module.exports
or exports
.
Let's create a simple module that exports a function to add two numbers.
// add.js
function add(a, b) {
return a + b;
}
module.exports = add;
In this example, we define a function add
and then export it using module.exports
.
To use the module we created, we use require
.
// main.js
const add = require('./add');
console.log(add(1, 2)); // Outputs: 3
In this example, we import the add
module using require
and then use it to add two numbers.
In this tutorial, we learned how to create and export custom modules in Node.js. Creating modules helps us organize our code into separate parts with a well-defined interface.
Create a module that exports a function to subtract two numbers. Use the module in a separate file.
Create a module that exports an object with four functions: add
, subtract
, multiply
, divide
. Each function should take two numbers and perform the respective operation. Use this module in a separate file.
// subtract.js
function subtract(a, b) {
return a - b;
}
module.exports = subtract;
Use the module:
// main.js
const subtract = require('./subtract');
console.log(subtract(5, 3)); // Outputs: 2
// calculator.js
module.exports = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => a / b
};
Use the module:
// main.js
const calculator = require('./calculator');
console.log(calculator.add(1, 2)); // Outputs: 3
console.log(calculator.subtract(5, 3)); // Outputs: 2
console.log(calculator.multiply(2, 3)); // Outputs: 6
console.log(calculator.divide(8, 2)); // Outputs: 4