Logo

Developer learning path

Node.js

Creating and Exporting Modules in Node.js

Creating and Exporting Modules

34

#description

Node.js modules are separate units of code that can be imported and used in other parts of your application. Modules can help you organize your code and allow multiple developers to work on different parts of your application at the same time.

Creating a module in Node.js is easy. You can create a new file and write your module code in that file. For example, let's say you want to create a module that calculates the area of a circle.

You can create a new file called circle.js and write the code for your module in that file:

                    
// circle.js
const PI = 3.14159;

function calculateArea(radius) {
  return PI * radius * radius;
}

module.exports = {
  calculateArea
};
                  

In this example, we define a constant called PI and a function called calculateArea that takes a radius parameter and returns the calculated area of a circle. We then use the module.exports object to export our calculateArea function, making it available for other parts of our application to use.

To use this module in another file, you can simply import it using the require function:

                    
// index.js
const circle = require('./circle.js');

console.log(`The area of a circle with radius 5 is ${circle.calculateArea(5)}`);
                  

In this example, we import the circle.js module using require and store the exported calculateArea function in a variable called circle. We then use the circle.calculateArea function to calculate and log the area of a circle with a radius of 5.

That's it! With Node.js modules, you can easily break your application down into smaller, more manageable pieces of code and reuse that code in multiple parts of your application.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.