Day 2: Modules and NPM
Chapter 2 • Beginner
Modules are reusable pieces of code that can be shared across different parts of your application. Node.js has a built-in module system that allows you to organize your code into separate files.
Built-in Modules:
Node.js comes with many built-in modules that provide core functionality:
- fs - File system operations
- http - HTTP server and client
- path - File path utilities
- os - Operating system utilities
- crypto - Cryptographic functionality
- url - URL parsing and formatting
Creating Custom Modules:
You can create your own modules using module.exports to export functions, objects, or values. Other files can then import these modules using require().
NPM (Node Package Manager):
NPM is the default package manager for Node.js. It helps you install, manage, and share packages. The package.json file contains metadata about your project and its dependencies.
Installing Packages:
Use npm install to install packages locally or globally. Local packages are installed in node_modules folder and are specific to your project.
Package.json:
This file contains project metadata including name, version, dependencies, scripts, and more. It's essential for managing your Node.js project.
Hands-on Examples
Creating a Custom Module
// math.js - Custom module
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;
const divide = (a, b) => a / b;
module.exports = {
add,
subtract,
multiply,
divide
};
// app.js - Using the custom module
const math = require('./math');
console.log('Addition:', math.add(5, 3));
console.log('Subtraction:', math.subtract(10, 4));
console.log('Multiplication:', math.multiply(6, 7));
console.log('Division:', math.divide(20, 4));This example shows how to create a custom module with math functions and import it in another file using require().