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