Node.js ยท Chapter 4 of 43
Node.js Modules
Modules let you organize code into separate reusable files. Node.js treats every file as its own module with its own scope.
You export values from one file and import them into another, keeping large applications maintainable.
Creating a module
Use `module.exports` to expose functions, objects, or values from a file so other files can use them.
Using a module
Use `require()` to import built-in, third-party, or your own modules by path or name.
Example 1 (javascript)
// math.js
function add(a, b) { return a + b; }
module.exports = add;This file exports a single function using module.exports.
Example 2 (javascript)
// app.js
const add = require('./math.js');
console.log(add(2, 3));Output
5require() loads the exported function and it can be called directly.
Key points
- Every Node.js file is its own module.
- module.exports exposes values from a file.
- require() imports modules by relative path or name.
- Modules keep code organized and reusable.
๐ก Note: Built-in modules like `fs` and `path` don't need installation, just `require()`.
