Understanding Modules
In Node.js, each file is treated as a separate module. Modules help you organize your code into reusable pieces. Node.js supports two module systems: CommonJS (the traditional way) and ES Modules (the modern standard).
CommonJS Modules
The original module system in Node.js. Uses require() and module.exports.
Creating a module (math.js):
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
// Export multiple functions
module.exports = {
add,
subtract,
multiply
};
// Or export individually
// exports.add = add;
// exports.subtract = subtract;
Using the module (app.js):
// app.js
const math = require('./math');
console.log(math.add(5, 3)); // 8
console.log(math.subtract(10, 4)); // 6
console.log(math.multiply(3, 7)); // 21
// Destructuring import
const { add, multiply } = require('./math');
console.log(add(2, 2)); // 4
ES Modules (ESM)
The modern JavaScript module system. To use ES modules in Node.js, either use .mjs extension
or set "type": "module" in package.json.
Creating an ES module (utils.mjs):
// utils.mjs
export function greet(name) {
return `Hello, ${name}!`;
}
export const PI = 3.14159;
// Default export
export default class Calculator {
add(a, b) {
return a + b;
}
}
Using ES modules (app.mjs):
// app.mjs
import Calculator, { greet, PI } from './utils.mjs';
console.log(greet('World')); // Hello, World!
console.log(PI); // 3.14159
const calc = new Calculator();
console.log(calc.add(5, 3)); // 8
// Dynamic import
const module = await import('./utils.mjs');
Built-in Modules
Node.js comes with many built-in modules that don't need installation:
// File System
const fs = require('fs');
// Path utilities
const path = require('path');
// HTTP server
const http = require('http');
// Operating system info
const os = require('os');
// Event handling
const EventEmitter = require('events');
// URL parsing
const url = require('url');
// Cryptography
const crypto = require('crypto');
// Example: Using the os module
console.log('Platform:', os.platform());
console.log('CPU cores:', os.cpus().length);
console.log('Free memory:', os.freemem() / 1024 / 1024, 'MB');
console.log('Home directory:', os.homedir());
📦 NPM - Node Package Manager
NPM is the world's largest software registry with over 2 million packages. It comes bundled with Node.js and allows you to install, share, and manage project dependencies.
Initializing a Project
# Create a new project with package.json
npm init
# Quick initialization with defaults
npm init -y
# This creates package.json with project metadata
Example package.json:
{
"name": "my-nodejs-app",
"version": "1.0.0",
"description": "My first Node.js application",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js",
"test": "jest"
},
"keywords": ["nodejs", "learning"],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"jest": "^29.7.0"
}
}
Installing Packages
# Install a package (adds to dependencies)
npm install express
npm i express # shorthand
# Install as dev dependency
npm install --save-dev jest
npm i -D jest # shorthand
# Install globally (CLI tools)
npm install -g nodemon
# Install specific version
npm install express@4.18.2
# Install all dependencies from package.json
npm install
# Uninstall a package
npm uninstall express
Using Installed Packages
// After: npm install lodash
const _ = require('lodash');
const numbers = [1, 2, 3, 4, 5];
console.log(_.sum(numbers)); // 15
console.log(_.shuffle(numbers)); // [3, 1, 5, 2, 4]
// Option 1: Native fetch (Node.js 18+)
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
// Option 2: Using axios (npm install axios)
const axios = require('axios');
async function fetchDataAxios() {
const response = await axios.get('https://api.example.com/data');
console.log(response.data);
}
// After: npm install dayjs
const dayjs = require('dayjs');
console.log(dayjs().format('YYYY-MM-DD')); // 2026-01-09
NPM Scripts
Define custom commands in package.json scripts section:
{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"build": "tsc",
"test": "jest",
"lint": "eslint .",
"format": "prettier --write ."
}
}
# Run npm scripts
npm run start # or just: npm start
npm run dev
npm test # shorthand for npm run test
npm run build
🔒 package-lock.json
This file locks the exact versions of all dependencies. Always commit it to version control to ensure consistent installations across different environments.
💡 Key Takeaways
- • Use CommonJS (require/exports) or ES Modules (import/export)
- • Node.js has many built-in modules (fs, path, http, etc.)
- • npm init creates a package.json for your project
- • Install packages with npm install package-name
- • Define scripts in package.json for common tasks