Node.js API Reference & Cheatsheet
DodaTech
Updated 2026-06-06
4 min read
In this tutorial, you'll learn about Node.js API Reference & Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Learning Path
flowchart LR
A["Nodejs Overview"] --> B["Core Concepts"]
B --> C["Intermediate Topics"]
C --> D["Advanced Topics"]
D --> E["Practical Applications"]
A --> F["You Are Here"]
style F fill:#f90,color:#fff
A comprehensive reference for daily Node.js development — keep this open while coding.
Running Node.js
node app.js # Run a file
node --watch app.js # Auto-restart on change (Node 18+)
node -e "console.log('hi')" # Inline script
node # REPL interactive shell
Module Systems
// CommonJS (default)
const fs = require("node:fs");
module.exports = { myFn };
// ES Modules (add "type": "module" to package.json)
import fs from "node:fs";
export function myFn() {}
Core Modules
| Module | Purpose |
|---|---|
fs / fs/promises |
File system operations |
path |
Path manipulation |
http / https |
HTTP server and client |
os |
Operating system info |
events |
EventEmitter pattern |
stream |
Streaming data |
buffer |
Binary data |
crypto |
Hashing, encryption, UUID |
child_Process |
Spawn subprocesses |
cluster |
Multi-core scaling |
worker_threads |
CPU task offloading |
readline |
Terminal input |
util |
Promisify, inspect, types |
zlib |
Compression (gzip, deflate) |
net / tls |
TCP/TLS sockets |
dgram |
UDP sockets |
npm Commands
npm init -y # Create package.json
npm install <pkg> # Install dependency
npm install -D <pkg> # Dev dependency
npm uninstall <pkg> # Remove
npm update # Update all packages
npm audit # Security audit
npm run <script> # Run script
npx <pkg> # Execute without install
Async Patterns
// Callback (error-first)
fs.readFile("f.txt", (err, data) => { if (err) throw err; });
// Promise
const data = await fs.promises.readFile("f.txt", "utf8");
// Parallel
const [a, b] = await Promise.all([p1, p2]);
// EventEmitter
const ee = new EventEmitter();
ee.on("event", handler);
ee.emit("event", data);
// promisify
const readFile = require("util").promisify(fs.readFile);
Express.js Quick Reference
const express = require("express");
const app = express();
app.use(express.json()); // Body parser
app.use(express.static("public")); // Static files
app.use(helmet()); // Security headers
app.use(cors()); // CORS
app.use(morgan("dev")); // Logging
app.get("/", (req, res) => res.json({}));
app.get("/:id", (req, res) => { req.params.id; req.query; });
const router = express.Router(); // Modular routes
app.use("/api", router);
// Error handler (4 params)
app.use((err, req, res, next) => {
res.status(err.status || 500).json({ error: err.message });
});
app.listen(3000);
Database Cheatsheet
MySQL (mysql2)
const pool = require("mysql2/promise").createPool({ host, user, database });
await pool.execute("SELECT * FROM users WHERE id = ?", [id]);
MongoDB (native)
const { MongoClient } = require("mongodb");
const db = await MongoClient.connect(uri).then(c => c.db("db"));
await db.collection("users").findOne({ _id: new ObjectId(id) });
Mongoose
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/db");
const User = mongoose.model("User", new mongoose.Schema({ name: String }));
await User.create({ name: "Alice" });
Security
npm install helmet cors express-rate-limit bcrypt express-validator dotenv
app.use(helmet());
app.use(cors({ origin: "https://example.com" }));
app.use(rateLimit({ windowMs: 15*60*1000, max: 100 }));
const hash = await bcrypt.hash(password, 12);
Testing
test("GET /api/health", async () => {
const res = await request(app).get("/api/health");
expect(res.status).toBe(200);
});
WebSockets (Socket.IO)
const { Server } = require("socket.io");
const io = new Server(httpServer);
io.on("connection", (socket) => {
socket.on("event", (data) => io.emit("event", data));
socket.join("room");
io.to("room").emit("event", data);
});
Deployment
npm install -g pm2
pm2 start app.js -i max # Cluster mode
pm2 save && pm2 startup # Auto-start on reboot
NODE_ENV=production node app.js # Production mode
Useful Packages
| Package | Purpose |
|---|---|
<a href="/backend/nodejs/">express</a> |
Web framework |
mongoose |
MongoDB ODM |
mysql2 |
MySQL driver |
dotenv |
Environment variables |
cors |
Cross-origin requests |
helmet |
Security headers |
morgan |
HTTP logging |
<a href="/backend/nodejs/">express</a>-rate-limit |
Rate Limiting |
bcrypt |
Password hashing |
jsonwebtoken |
JWT auth |
socket.io |
WebSockets |
multer |
File uploads |
joi |
Input validation |
jest + supertest |
Testing |
pm2 |
Process manager |
Common Mistakes
- Assuming all features work identically — always check browser/version compatibility.
- Skipping documentation — reference docs exist for a reason; consult them.
- Not testing edge cases — your setup may differ from tutorials.
- Overlooking security — always validate inputs and follow best practices.
- Copy-pasting without understanding — type code yourself to build real knowledge.
What's Next
| Lesson | Description |
|---|---|
| {{< ref "express.md" >}} | Express.js framework |
| {{< ref "nodejs-advanced.md" >}} | Clustering, WebSockets |
| {{< ref "../php/php-reference.md" >}} | PHP reference |
| Docker | Containerization |
| REST API | API Design Patterns |
← Previous
Koa.js Guide — Modern Node.js Framework by Express Creators
Next →
Node.js Global Objects — Complete Guide to Global, Process, Buffer, and Console
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro