Creating My First Module: Node.js Tutorial

Posted by

Node.js Tutorial | Creando Mi Primer Modulo

Node.js Tutorial | Creando Mi Primer Modulo

Node.js is a powerful and popular JavaScript runtime that is used for building server-side applications. In this tutorial, we will learn how to create our first module in Node.js.

What is a Module in Node.js?

A module in Node.js is a reusable block of code that encapsulates a set of related functionality. It can be a single file or a folder containing multiple files. Modules can be included in other Node.js applications to use their functionality.

Creating our First Module

Let’s create a simple module that exports a function to calculate the square of a number. Create a new file named square.js with the following code:


const calculateSquare = (number) => {
return number * number;
}

module.exports = calculateSquare;

In the above code, we define a function calculateSquare that takes a number as input and returns its square. We then use the module.exports to export this function as a module.

Using our Module in a Node.js Application

Create a new file named app.js where we will use our square module. Here is the code for app.js:


const square = require('./square');

console.log(square(5)); // Output: 25

In the above code, we use the require function to include our square module and then call the square function to calculate the square of the number 5 and print the result to the console.

Conclusion

Congratulations! You have created your first module in Node.js. This is just the beginning of your journey with Node.js, and there is a lot more to explore and learn. Keep experimenting with different modules and functionalities to strengthen your Node.js skills.