Skip to content
Node.js API Reference & Cheatsheet

Node.js API Reference & Cheatsheet

DodaTech Updated Jun 6, 2026 3 min read

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

ModulePurpose
fs / fs/promisesFile system operations
pathPath manipulation
http / httpsHTTP server and client
osOperating system info
eventsEventEmitter pattern
streamStreaming data
bufferBinary data
cryptoHashing, encryption, UUID
child_processSpawn subprocesses
clusterMulti-core scaling
worker_threadsCPU task offloading
readlineTerminal input
utilPromisify, inspect, types
zlibCompression (gzip, deflate)
net / tlsTCP/TLS sockets
dgramUDP 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

PackagePurpose
expressWeb framework
mongooseMongoDB ODM
mysql2MySQL driver
dotenvEnvironment variables
corsCross-origin requests
helmetSecurity headers
morganHTTP logging
express-rate-limitRate limiting
bcryptPassword hashing
jsonwebtokenJWT auth
socket.ioWebSockets
multerFile uploads
joiInput validation
jest + supertestTesting
pm2Process manager

Common Mistakes

  1. Assuming all features work identically — always check browser/version compatibility.
  2. Skipping documentation — reference docs exist for a reason; consult them.
  3. Not testing edge cases — your setup may differ from tutorials.
  4. Overlooking security — always validate inputs and follow best practices.
  5. Copy-pasting without understanding — type code yourself to build real knowledge.

What’s Next

LessonDescription
https://tutorials.dodatech.com/backend/nodejs/express/Express.js framework
https://tutorials.dodatech.com/backend/nodejs/nodejs-advanced/Clustering, WebSockets
https://tutorials.dodatech.com/backend/php/php-reference/PHP reference
DockerContainerization
REST APIAPI design patterns

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro