0
0
Node.jsframework~15 mins

CommonJS require and module.exports in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
CommonJS require and module.exports
📖 Scenario: You are building a simple Node.js app that uses CommonJS modules to organize code. You want to create a module that exports a greeting function, then import and use it in your main file.
🎯 Goal: Create a module file that exports a function using module.exports, then import it in another file using require and call the function.
📋 What You'll Learn
Create a file named greet.js that exports a function called sayHello using module.exports.
The sayHello function should return the string 'Hello, Node.js!'.
Create a file named app.js that imports the sayHello function from greet.js using require.
Call the imported sayHello function in app.js.
💡 Why This Matters
🌍 Real World
Node.js uses CommonJS modules to organize code into reusable pieces. This helps keep projects clean and manageable.
💼 Career
Understanding CommonJS modules is essential for backend JavaScript development and working with many Node.js projects.
Progress0 / 4 steps
1
Create the greet.js module with sayHello function
Create a file named greet.js. Inside it, define a function called sayHello that returns the string 'Hello, Node.js!'.
Node.js
Need a hint?

Define a function named sayHello that returns the greeting string.

2
Export the sayHello function using module.exports
In greet.js, export the sayHello function using module.exports.
Node.js
Need a hint?

Assign the sayHello function to module.exports to export it.

3
Import the sayHello function in app.js using require
Create a file named app.js. Import the sayHello function from greet.js using require and store it in a variable called sayHello.
Node.js
Need a hint?

Use require('./greet') to import the exported function and assign it to sayHello.

4
Call the sayHello function in app.js
In app.js, call the sayHello function.
Node.js
Need a hint?

Simply call the sayHello() function to use it.