0
0
Node.jsframework~30 mins

Why modules are needed in Node.js - See It in Action

Choose your learning style9 modes available
Why modules are needed in Node.js
📖 Scenario: You are building a simple Node.js program that calculates areas of different shapes. To keep your code clean and organized, you want to separate the area calculations into a module.
🎯 Goal: Create a Node.js module for area calculations and use it in your main program to calculate areas of a rectangle and a circle.
📋 What You'll Learn
Create a module file named area.js exporting functions for rectangle and circle area calculations
Create a main file named app.js that imports the area.js module
Use the imported functions to calculate and store the area of a rectangle with width 5 and height 10
Use the imported functions to calculate and store the area of a circle with radius 7
💡 Why This Matters
🌍 Real World
In real projects, modules keep code organized and allow teams to work on different parts without conflicts.
💼 Career
Understanding modules is essential for Node.js developers to build scalable and maintainable applications.
Progress0 / 4 steps
1
Create the area.js module with rectangle area function
Create a file named area.js and write a function called rectangleArea that takes width and height as parameters and returns their product. Export this function using module.exports.
Node.js
Need a hint?

Remember to export your function so other files can use it.

2
Add circle area function to area.js
In area.js, add a function called circleArea that takes radius as a parameter and returns the area using Math.PI * radius * radius. Export this function alongside rectangleArea.
Node.js
Need a hint?

Use Math.PI for the circle area calculation.

3
Create app.js and import area.js module
Create a file named app.js. Import the area.js module using require and store it in a variable called area.
Node.js
Need a hint?

Use require('./area') to import the module.

4
Use imported functions to calculate areas in app.js
In app.js, use area.rectangleArea to calculate the area of a rectangle with width 5 and height 10, and store it in a variable called rectArea. Then use area.circleArea to calculate the area of a circle with radius 7, and store it in a variable called circleAreaValue.
Node.js
Need a hint?

Call the functions from the imported area object with the exact arguments.