Skip to main content

Node.js Cheatsheet

Comprehensive quick reference for Node.js runtime, core modules, async operations, streams, file system, HTTP servers, npm, and best practices. Essential guide for Node.js 20+.

Table of Contents


Prerequisites

Node.js Version: This cheatsheet targets Node.js 20.0+ (LTS). Some features require specific versions (noted inline).

System Requirements:

  • macOS: 10.15+ (64-bit)
  • Linux: Most distributions (64-bit)
  • Windows: Windows 10/11 (64-bit) or WSL 2

Prerequisites:

  • Basic JavaScript knowledge
  • Command-line familiarity
  • Understanding of async programming concepts

Installation & Version Management

Installation Commands πŸ”§

Terminal window
# Check Node.js version
node --version
# β†’ v20.11.0
# Check npm version
npm --version
# β†’ 10.2.4
# Check all versions (Node, npm, V8)
node -p "process.versions"
# β†’ { node: '20.11.0', v8: '11.3.244.8', ... }
# Install Node.js via nvm (recommended)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install 20
nvm use 20
nvm alias default 20
# Install Node.js via Homebrew (macOS)
brew install node@20
# Install Node.js via apt (Ubuntu/Debian)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs

Version Management πŸ”„

Terminal window
# List installed Node.js versions (nvm)
nvm list
# Install specific version
nvm install 18.20.0
# Switch to version
nvm use 18.20.0
# Set default version
nvm alias default 20.11.0
# List available versions
nvm list-remote
# Check current version
nvm current
# β†’ v20.11.0

Node.js REPL πŸ’»

Terminal window
# Start Node.js REPL
node
# In REPL:
# .help - Show help
# .exit - Exit REPL
# .clear - Clear context
# .load <file> - Load file
# .save <file> - Save session
# Execute file
node script.js
# Execute with eval
node -e "console.log('Hello')"
# β†’ Hello
# Execute with stdin
echo "console.log('Hi')" | node
# β†’ Hi

Core Modules

Module System πŸ“¦

// CommonJS (require/module.exports)
const fs = require("fs");
const { readFile } = require("fs"); // Named import
module.exports = { myFunction };
module.exports.myFunction = myFunction; // Named export
// ES Modules (import/export) - Node.js 12.20+, 14.13+, or 16+
// In package.json: "type": "module"
import fs from "fs";
import { readFile } from "fs";
import * as fs from "fs";
export default myFunction;
export { myFunction };
export { myFunction as renamed };
// Mixed usage (CommonJS importing ES Module)
const { default: myFunction } = await import("./module.mjs");
// ES Module importing CommonJS
import pkg from "./commonjs.cjs";
const { myFunction } = pkg;

Path Module πŸ—ΊοΈ

const path = require("path");
// Join paths (handles separators)
path.join("/foo", "bar", "baz/asdf", "quux", "..");
// β†’ '/foo/bar/baz/asdf'
// Resolve absolute path
path.resolve("foo/bar", "/tmp/file/", "..", "a/../subfile");
// β†’ '/tmp/subfile'
// Get directory name
path.dirname("/foo/bar/baz/asdf/quux");
// β†’ '/foo/bar/baz/asdf'
// Get filename
path.basename("/foo/bar/baz/asdf/quux.html");
// β†’ 'quux.html'
// Get filename without extension
path.basename("/foo/bar/baz/asdf/quux.html", ".html");
// β†’ 'quux'
// Get extension
path.extname("index.html");
// β†’ '.html'
// Parse path object
path.parse("/home/user/dir/file.txt");
// β†’ { root: '/', dir: '/home/user/dir', base: 'file.txt', ext: '.txt', name: 'file' }
// Format path from object
path.format({ dir: "/home/user/dir", base: "file.txt" });
// β†’ '/home/user/dir/file.txt'
// Normalize path (resolve . and ..)
path.normalize("/foo/bar//baz/asdf/quux/..");
// β†’ '/foo/bar/baz/asdf'
// Check if absolute path
path.isAbsolute("/foo/bar"); // β†’ true
path.isAbsolute("./bar"); // β†’ false
// Get relative path
path.relative("/data/orandea/test/aaa", "/data/orandea/impl/bbb");
// β†’ '../../impl/bbb'

URL Module 🌐

const { URL } = require("url");
// Parse URL
const myURL = new URL("https://example.org:8080/foo/bar?abc=123#section");
console.log(myURL.href); // β†’ 'https://example.org:8080/foo/bar?abc=123#section'
console.log(myURL.protocol); // β†’ 'https:'
console.log(myURL.hostname); // β†’ 'example.org'
console.log(myURL.port); // β†’ '8080'
console.log(myURL.pathname); // β†’ '/foo/bar'
console.log(myURL.search); // β†’ '?abc=123'
console.log(myURL.hash); // β†’ '#section'
// URLSearchParams
const params = new URLSearchParams("foo=bar&baz=qux");
params.get("foo"); // β†’ 'bar'
params.set("foo", "new"); // Set value
params.append("foo", "another"); // Add another value
params.delete("baz"); // Delete param
params.toString(); // β†’ 'foo=new&foo=another'
// File URL
const fileUrl = new URL("file:///C:/path/to/file.txt");

Util Module πŸ› οΈ

const util = require("util");
// Promisify callback-based function
const fs = require("fs");
const readFile = util.promisify(fs.readFile);
const fileContent = await readFile("file.txt", "utf8");
// Inspect object (debugging)
util.inspect({ a: 1, b: { c: 2 } }, { depth: 2, colors: true });
// Format string (like printf)
util.format("%s:%s", "foo", "bar", "baz");
// β†’ 'foo:bar baz'
// Check types
util.types.isDate(new Date()); // β†’ true
util.types.isRegExp(/abc/); // β†’ true
util.types.isPromise(Promise.resolve()); // β†’ true
// Inherit (deprecated, use ES6 classes)
util.inherits(MyStream, stream.Stream);
// Callbackify (convert promise to callback)
const callbackFn = util.callbackify(asyncFn);
callbackFn((err, result) => {
/* ... */
});

Buffer Module πŸ“Š

const { Buffer } = require("buffer");
// Create buffer
const buf1 = Buffer.alloc(10); // Zero-filled
const buf2 = Buffer.allocUnsafe(10); // Uninitialized (faster)
const buf3 = Buffer.from("hello"); // From string
const buf4 = Buffer.from([1, 2, 3]); // From array
const buf5 = Buffer.from("hello", "utf8"); // With encoding
// Buffer operations
buf1.write("hello", 0, "utf8");
buf1.toString("utf8"); // β†’ 'hello'
buf1.toString("hex"); // β†’ '68656c6c6f'
buf1.toString("base64"); // β†’ 'aGVsbG8='
// Buffer methods
buf1.length; // β†’ 10
buf1.slice(0, 5); // β†’ New buffer (shares memory)
buf1.copy(buf2, 0, 0, 5); // Copy to another buffer
Buffer.concat([buf1, buf2]); // Concatenate buffers
Buffer.isBuffer(buf1); // β†’ true
// Buffer comparison
buf1.equals(buf2); // β†’ false
buf1.compare(buf2); // β†’ -1, 0, or 1

Crypto Module πŸ”

const crypto = require("crypto");
// Hash
const hash = crypto.createHash("sha256");
hash.update("hello");
hash.digest("hex");
// β†’ '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
// HMAC
const hmac = crypto.createHmac("sha256", "secret-key");
hmac.update("hello");
hmac.digest("hex");
// Random bytes
crypto.randomBytes(16, (err, buf) => {
console.log(buf.toString("hex"));
});
// Synchronous random bytes
const randomBuf = crypto.randomBytes(16);
// Create cipher
const cipher = crypto.createCipher("aes192", "password");
let encrypted = cipher.update("hello", "utf8", "hex");
encrypted += cipher.final("hex");
// Create decipher
const decipher = crypto.createDecipher("aes192", "password");
let decrypted = decipher.update(encrypted, "hex", "utf8");
decrypted += decipher.final("utf8");

File System Operations

Reading Files πŸ“–

const fs = require("fs");
const fsPromises = require("fs").promises;
// Synchronous read (blocking)
const data = fs.readFileSync("file.txt", "utf8");
console.log(data);
// Asynchronous read (callback)
fs.readFile("file.txt", "utf8", (err, data) => {
if (err) throw err;
console.log(data);
});
// Promise-based read (Node.js 10+)
const data = await fsPromises.readFile("file.txt", "utf8");
// Read with options
const data = await fsPromises.readFile("file.txt", {
encoding: "utf8",
flag: "r",
});
// Read binary file
const buffer = await fsPromises.readFile("image.png");

Writing Files ✍️

const fs = require("fs");
const fsPromises = require("fs").promises;
// Synchronous write
fs.writeFileSync("file.txt", "Hello World", "utf8");
// Asynchronous write
fs.writeFile("file.txt", "Hello World", "utf8", (err) => {
if (err) throw err;
console.log("File written");
});
// Promise-based write
await fsPromises.writeFile("file.txt", "Hello World", "utf8");
// Append to file
fs.appendFileSync("file.txt", "\nNew line", "utf8");
await fsPromises.appendFile("file.txt", "\nNew line", "utf8");
// Write with options
await fsPromises.writeFile("file.txt", "content", {
encoding: "utf8",
mode: 0o666,
flag: "w", // 'w' write, 'a' append, 'r+' read/write
});

Directory Operations πŸ“

const fs = require("fs");
const fsPromises = require("fs").promises;
// Create directory
fs.mkdirSync("newdir");
await fsPromises.mkdir("newdir");
// Create directory recursively
fs.mkdirSync("path/to/dir", { recursive: true });
await fsPromises.mkdir("path/to/dir", { recursive: true });
// Read directory
const files = fs.readdirSync("dir");
const files = await fsPromises.readdir("dir");
// Read directory with options
const files = await fsPromises.readdir("dir", {
encoding: "utf8",
withFileTypes: true, // Returns Dirent objects
});
// Remove directory
fs.rmdirSync("dir");
await fsPromises.rmdir("dir");
// Remove directory recursively (Node.js 14.14+)
fs.rmSync("dir", { recursive: true });
await fsPromises.rm("dir", { recursive: true });
// Check if path exists
if (fs.existsSync("file.txt")) {
// File exists
}
// Check if path exists (async)
const exists = await fsPromises
.access("file.txt")
.then(() => true)
.catch(() => false);

File Stats & Metadata πŸ“Š

const fs = require("fs");
const fsPromises = require("fs").promises;
// Get file stats
const stats = fs.statSync("file.txt");
const stats = await fsPromises.stat("file.txt");
// Check file type
stats.isFile(); // β†’ true/false
stats.isDirectory(); // β†’ true/false
stats.isSymbolicLink(); // β†’ true/false
// File properties
stats.size; // File size in bytes
stats.mtime; // Modified time
stats.ctime; // Created time
stats.mode; // File mode (permissions)
stats.uid; // User ID
stats.gid; // Group ID
// Watch file changes
const watcher = fs.watch("file.txt", (eventType, filename) => {
console.log(`Event: ${eventType}, File: ${filename}`);
});
// Watch directory
const watcher = fs.watch("dir", { recursive: true }, (eventType, filename) => {
console.log(`Event: ${eventType}, File: ${filename}`);
});
watcher.close(); // Stop watching

File Operations πŸ”„

const fs = require("fs");
const fsPromises = require("fs").promises;
// Copy file
fs.copyFileSync("source.txt", "dest.txt");
await fsPromises.copyFile("source.txt", "dest.txt");
// Copy with flags
await fsPromises.copyFile("source.txt", "dest.txt", fs.constants.COPYFILE_EXCL);
// Rename/move file
fs.renameSync("old.txt", "new.txt");
await fsPromises.rename("old.txt", "new.txt");
// Delete file
fs.unlinkSync("file.txt");
await fsPromises.unlink("file.txt");
// Change permissions
fs.chmodSync("file.txt", 0o755);
await fsPromises.chmod("file.txt", 0o755);
// Change ownership
fs.chownSync("file.txt", 1000, 1000);
await fsPromises.chown("file.txt", 1000, 1000);
// Create symlink
fs.symlinkSync("target", "link");
await fsPromises.symlink("target", "link");
// Read symlink
const target = fs.readlinkSync("link");
const target = await fsPromises.readlink("link");

HTTP & Web Servers

HTTP Server 🌐

const http = require("http");
// Create HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello World\n");
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
// Server with routing
const server = http.createServer((req, res) => {
const { method, url } = req;
if (method === "GET" && url === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Home</h1>");
} else if (method === "GET" && url === "/api/users") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify([{ id: 1, name: "John" }]));
} else {
res.writeHead(404);
res.end("Not Found");
}
});
server.listen(3000);

HTTP Client πŸ“‘

const http = require("http");
// GET request
const options = {
hostname: "example.com",
port: 80,
path: "/api/data",
method: "GET",
headers: {
"User-Agent": "Node.js",
},
};
const req = http.request(options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
console.log(JSON.parse(data));
});
});
req.on("error", (error) => {
console.error(error);
});
req.end();
// GET request (simplified)
http.get("http://example.com/api/data", (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
console.log(data);
});
});

HTTPS Server & Client πŸ”’

const https = require("https");
const fs = require("fs");
// HTTPS server
const options = {
key: fs.readFileSync("key.pem"),
cert: fs.readFileSync("cert.pem"),
};
const server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end("Hello HTTPS");
});
server.listen(443);
// HTTPS client
const options = {
hostname: "example.com",
port: 443,
path: "/api/data",
method: "GET",
rejectUnauthorized: true, // Verify certificate
};
const req = https.request(options, (res) => {
// Handle response
});
req.end();

URL Parsing in HTTP Requests πŸ”

const http = require("http");
const { URL } = require("url");
const server = http.createServer((req, res) => {
const baseURL = `http://${req.headers.host}/`;
const parsedUrl = new URL(req.url, baseURL);
// Access URL components
parsedUrl.pathname; // β†’ '/api/users'
parsedUrl.search; // β†’ '?id=123'
parsedUrl.searchParams.get("id"); // β†’ '123'
res.end("OK");
});

Async Operations

Promises ⏳

// Create promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Success");
// or reject(new Error('Failed'));
}, 1000);
});
// Promise chain
promise
.then((value) => {
console.log(value); // β†’ 'Success'
return "Next value";
})
.then((value) => {
console.log(value); // β†’ 'Next value'
})
.catch((error) => {
console.error(error);
})
.finally(() => {
console.log("Always executed");
});
// Promise.all (all must succeed)
Promise.all([promise1, promise2, promise3])
.then((results) => {
// All resolved
})
.catch((error) => {
// First rejection
});
// Promise.allSettled (wait for all)
Promise.allSettled([promise1, promise2]).then((results) => {
// All settled (resolved or rejected)
});
// Promise.race (first to settle)
Promise.race([promise1, promise2]).then((result) => {
// First resolved
});
// Promise.any (first to resolve)
Promise.any([promise1, promise2]).then((result) => {
// First resolved
});

Async/Await 🎯

// Async function
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
return data;
} catch (error) {
console.error("Error:", error);
throw error;
}
}
// Multiple async operations
async function fetchMultiple() {
// Sequential
const data1 = await fetchData1();
const data2 = await fetchData2();
// Parallel
const [data1, data2] = await Promise.all([fetchData1(), fetchData2()]);
return { data1, data2 };
}
// Async arrow function
const fetchData = async () => {
const data = await someAsyncOperation();
return data;
};
// Top-level await (ES Modules, Node.js 14.8+)
const data = await fetchData();

Callbacks vs Promises vs Async/Await πŸ”„

// Callback style (old)
fs.readFile("file.txt", "utf8", (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
// Promise style
fs.promises
.readFile("file.txt", "utf8")
.then((data) => console.log(data))
.catch((err) => console.error(err));
// Async/await style (modern)
try {
const data = await fs.promises.readFile("file.txt", "utf8");
console.log(data);
} catch (err) {
console.error(err);
}

Event Loop Understanding πŸ”

// Microtasks vs Macrotasks
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
process.nextTick(() => console.log("4"));
console.log("5");
// Output: 1, 5, 4, 3, 2
// Order: sync β†’ nextTick β†’ promises β†’ timers
// process.nextTick (highest priority)
process.nextTick(() => {
console.log("Next tick");
});
// setImmediate (check phase)
setImmediate(() => {
console.log("Immediate");
});
// setTimeout (timers phase)
setTimeout(() => {
console.log("Timeout");
}, 0);

Streams

Readable Streams πŸ“₯

const fs = require("fs");
// Create readable stream
const readable = fs.createReadStream("large-file.txt", {
encoding: "utf8",
highWaterMark: 64 * 1024, // 64KB chunks
});
// Read data
readable.on("data", (chunk) => {
console.log(`Received ${chunk.length} bytes`);
});
readable.on("end", () => {
console.log("Finished reading");
});
readable.on("error", (err) => {
console.error("Error:", err);
});
// Pause and resume
readable.pause();
readable.resume();
// Custom readable stream
const { Readable } = require("stream");
const readable = new Readable({
read() {
this.push("chunk");
this.push(null); // End stream
},
});

Writable Streams πŸ“€

const fs = require("fs");
// Create writable stream
const writable = fs.createWriteStream("output.txt");
// Write data
writable.write("Hello ");
writable.write("World");
writable.end("\nDone");
// Events
writable.on("finish", () => {
console.log("Finished writing");
});
writable.on("error", (err) => {
console.error("Error:", err);
});
// Custom writable stream
const { Writable } = require("stream");
const writable = new Writable({
write(chunk, encoding, callback) {
console.log(chunk.toString());
callback(); // Signal completion
},
});

Transform Streams πŸ”„

const { Transform } = require("stream");
// Transform stream (readable + writable)
const transform = new Transform({
transform(chunk, encoding, callback) {
// Transform data
const upper = chunk.toString().toUpperCase();
this.push(upper);
callback();
},
});
// Usage
process.stdin.pipe(transform).pipe(process.stdout);
// Example: Uppercase transform
const upperCase = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().toUpperCase());
},
});
fs.createReadStream("input.txt")
.pipe(upperCase)
.pipe(fs.createWriteStream("output.txt"));

Piping Streams πŸ”—

const fs = require("fs");
// Basic pipe
fs.createReadStream("input.txt").pipe(fs.createWriteStream("output.txt"));
// Pipe with error handling
const readStream = fs.createReadStream("input.txt");
const writeStream = fs.createWriteStream("output.txt");
readStream.pipe(writeStream);
readStream.on("error", (err) => {
writeStream.destroy();
console.error("Read error:", err);
});
writeStream.on("error", (err) => {
readStream.destroy();
console.error("Write error:", err);
});
// Pipe with transform
const { pipeline } = require("stream");
const zlib = require("zlib");
pipeline(
fs.createReadStream("input.txt"),
zlib.createGzip(),
fs.createWriteStream("output.txt.gz"),
(err) => {
if (err) {
console.error("Pipeline failed:", err);
} else {
console.log("Pipeline succeeded");
}
},
);

Process & Environment

Process Object πŸ–₯️

// Process arguments
process.argv;
// β†’ ['/path/to/node', '/path/to/script.js', 'arg1', 'arg2']
// Environment variables
process.env.NODE_ENV;
process.env.PORT || 3000;
// Process ID
process.pid;
// Current working directory
process.cwd();
process.chdir("/new/path");
// Exit process
process.exit(0); // Success
process.exit(1); // Error
// Exit handlers
process.on("exit", (code) => {
console.log(`Exiting with code ${code}`);
});
process.on("beforeExit", (code) => {
console.log("Before exit");
});
// Uncaught exception
process.on("uncaughtException", (err) => {
console.error("Uncaught exception:", err);
process.exit(1);
});
// Unhandled promise rejection
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled rejection:", reason);
});
// Signals
process.on("SIGINT", () => {
console.log("Received SIGINT");
process.exit(0);
});
process.on("SIGTERM", () => {
console.log("Received SIGTERM");
process.exit(0);
});

Environment Variables 🌍

// Access environment variables
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
const nodeEnv = process.env.NODE_ENV || "development";
// Set environment variable (runtime)
process.env.MY_VAR = "value";
// Load from .env file (requires dotenv package)
require("dotenv").config();
// Then access: process.env.MY_VAR
// Check if production
const isProduction = process.env.NODE_ENV === "production";
// Environment-specific config
const config = {
development: {
apiUrl: "http://localhost:3000",
},
production: {
apiUrl: "https://api.example.com",
},
}[process.env.NODE_ENV || "development"];

Command Line Arguments πŸ“

// Parse arguments manually
const args = process.argv.slice(2);
const command = args[0];
const options = args.slice(1);
// Using minimist (npm package)
const minimist = require("minimist");
const args = minimist(process.argv.slice(2));
// node script.js --port=3000 --debug
// β†’ { _: [], port: 3000, debug: true }
// Using yargs (npm package)
const yargs = require("yargs");
const argv = yargs
.option("port", {
alias: "p",
type: "number",
default: 3000,
})
.option("debug", {
alias: "d",
type: "boolean",
default: false,
}).argv;

Error Handling

Try/Catch ⚠️

// Basic try/catch
try {
riskyOperation();
} catch (error) {
console.error("Error:", error.message);
console.error("Stack:", error.stack);
}
// Try/catch with async
try {
const data = await asyncOperation();
} catch (error) {
if (error.code === "ENOENT") {
console.error("File not found");
} else {
console.error("Unknown error:", error);
}
}
// Multiple catch blocks (not supported, use if/else)
try {
await operation();
} catch (error) {
if (error instanceof TypeError) {
// Handle TypeError
} else if (error instanceof ReferenceError) {
// Handle ReferenceError
} else {
// Handle other errors
}
}

Error Types 🚨

// Create custom error
class CustomError extends Error {
constructor(message, code) {
super(message);
this.name = "CustomError";
this.code = code;
}
}
throw new CustomError("Something went wrong", "CUSTOM_001");
// Common error types
throw new Error("Generic error");
throw new TypeError("Type error");
throw new ReferenceError("Reference error");
throw new SyntaxError("Syntax error");
throw new RangeError("Range error");
// Error with stack trace
const error = new Error("Error message");
console.error(error.stack);

Error Handling Patterns 🎯

// Callback error handling
function callbackStyle(callback) {
fs.readFile("file.txt", (err, data) => {
if (err) {
return callback(err); // Early return
}
callback(null, data);
});
}
// Promise error handling
function promiseStyle() {
return fs.promises.readFile("file.txt").catch((err) => {
// Handle error
throw new Error(`Failed to read file: ${err.message}`);
});
}
// Async/await error handling
async function asyncStyle() {
try {
const data = await fs.promises.readFile("file.txt");
return data;
} catch (err) {
// Handle error
throw new Error(`Failed to read file: ${err.message}`);
}
}
// Error wrapper utility
function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}

Package Management

NPM Basics πŸ“¦

Terminal window
# Initialize package.json
npm init
npm init -y # Skip questions
# Install package
npm install package-name
npm install package-name --save-dev # Dev dependency
npm install package-name --save-optional # Optional dependency
npm install package-name --save-peer # Peer dependency
# Install specific version
npm install package-name@1.2.3
npm install package-name@^1.2.0 # Compatible version
npm install package-name@~1.2.0 # Patch version
npm install package-name@latest # Latest version
# Install from package.json
npm install
# Uninstall package
npm uninstall package-name
# Update package
npm update package-name
npm update # Update all packages
# List installed packages
npm list
npm list --depth=0 # Top level only
npm list package-name # Specific package
# Search packages
npm search query
# View package info
npm view package-name
npm view package-name versions # All versions
npm view package-name version # Latest version

Package.json Scripts πŸ“œ

{
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js",
"test": "jest",
"build": "tsc",
"lint": "eslint .",
"prestart": "echo 'Before start'",
"poststart": "echo 'After start'"
}
}
Terminal window
# Run script
npm start
npm run dev
npm run test
# Run with arguments
npm run script-name -- --arg value
# Pre and post scripts run automatically
npm start # Runs prestart β†’ start β†’ poststart

NPM Configuration βš™οΈ

Terminal window
# Set config
npm config set registry https://registry.npmjs.org/
npm config set save-exact true
npm config set save-prefix="~"
# Get config
npm config get registry
# List all config
npm config list
# Edit config file
npm config edit
# Remove config
npm config delete key
# Use different registry
npm install --registry https://registry.example.com
# Scoped packages
npm install @scope/package-name
npm publish --access public # For scoped packages

PNPM (Alternative) πŸš€

Terminal window
# Install pnpm
npm install -g pnpm
# Install packages (same as npm)
pnpm install package-name
pnpm add package-name --dev
# Run scripts
pnpm start
pnpm run script-name
# Benefits: Faster, disk-efficient, strict dependency resolution

Debugging & Profiling

Node.js Debugger πŸ›

Terminal window
# Start debugger
node inspect script.js
# With Chrome DevTools
node --inspect script.js
# Then open chrome://inspect in Chrome
# Break on start
node --inspect-brk script.js
# Debug with VS Code
# Add to .vscode/launch.json:
{
"type": "node",
"request": "launch",
"name": "Debug Node.js",
"program": "${workspaceFolder}/index.js",
"console": "integratedTerminal"
}

Console Methods πŸ“Š

// Basic logging
console.log("Info");
console.error("Error");
console.warn("Warning");
console.info("Info");
// Formatted output
console.log("User: %s, Age: %d", "John", 30);
console.log("Object: %j", { a: 1 });
// Table output
console.table([
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
]);
// Group logs
console.group("Group");
console.log("Item 1");
console.log("Item 2");
console.groupEnd();
// Time operations
console.time("operation");
// ... code ...
console.timeEnd("operation");
// Stack trace
console.trace("Trace message");
// Assert
console.assert(condition, "Message");

Performance Profiling ⚑

// Performance timing
const { performance } = require('perf_hooks');
const start = performance.now();
// ... code ...
const end = performance.now();
console.log(`Time: ${end - start}ms`);
// Performance marks
performance.mark('start');
// ... code ...
performance.mark('end');
performance.measure('duration', 'start', 'end');
// Memory usage
const used = process.memoryUsage();
console.log({
rss: `${Math.round(used.rss / 1024 / 1024 * 100) / 100} MB`,
heapTotal: `${Math.round(used.heapTotal / 1024 / 1024 * 100) / 100} MB`,
heapUsed: `${Math.round(used.heapUsed / 1024 / 1024 * 100) / 100} MB`,
external: `${Math.round(used.external / 1024 / 1024 * 100) / 100} MB`
});
// CPU profiling
node --prof script.js
node --prof-process isolate-*.log > processed.txt

Best Practices

βœ… Do’s

// βœ… Use async/await for async operations
async function fetchData() {
const data = await api.getData();
return data;
}
// βœ… Handle errors properly
try {
await operation();
} catch (error) {
logger.error(error);
throw error;
}
// βœ… Use const/let, avoid var
const data = "value";
let counter = 0;
// βœ… Use strict mode
("use strict");
// βœ… Use environment variables for config
const port = process.env.PORT || 3000;
// βœ… Use streams for large files
fs.createReadStream("large-file.txt")
.pipe(transform)
.pipe(fs.createWriteStream("output.txt"));
// βœ… Use process managers in production
// PM2, Forever, or systemd
// βœ… Validate input
if (!input || typeof input !== "string") {
throw new Error("Invalid input");
}
// βœ… Use meaningful error messages
throw new Error("Failed to connect to database: connection timeout");
// βœ… Clean up resources
stream.on("end", () => {
stream.destroy();
});

❌ Don’ts

// ❌ Don't use synchronous operations in async contexts
const data = fs.readFileSync("file.txt"); // Blocks event loop
// ❌ Don't ignore errors
fs.readFile("file.txt", (err, data) => {
// Missing error handling
console.log(data);
});
// ❌ Don't use var
var oldStyle = "avoid";
// ❌ Don't block the event loop
for (let i = 0; i < 1000000000; i++) {
// Heavy computation blocks event loop
}
// ❌ Don't use == (use ===)
if (value == null) {
} // Use ===
// ❌ Don't mutate function parameters
function process(data) {
data.value = "changed"; // Mutates original
}
// ❌ Don't create global variables
global.myVar = "bad"; // Avoid
// ❌ Don't use eval()
eval('console.log("bad")'); // Security risk
// ❌ Don't ignore promise rejections
promise.then(() => {}); // Missing .catch()

Code Organization πŸ“

utils/logger.js
// βœ… Separate concerns
module.exports = {
info: (msg) => console.log(`[INFO] ${msg}`),
error: (msg) => console.error(`[ERROR] ${msg}`),
};
// βœ… Use modules
// config/database.js
module.exports = {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
};
// βœ… Error handling middleware
function errorHandler(err, req, res, next) {
logger.error(err);
res.status(500).json({ error: "Internal server error" });
}
// βœ… Async wrapper for route handlers
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};

Common Pitfalls

⚠️ Blocking the Event Loop

// ❌ Bad: Synchronous operation blocks event loop
const data = fs.readFileSync("large-file.txt");
// βœ… Good: Use async/streams
const data = await fs.promises.readFile("large-file.txt");
// or
fs.createReadStream("large-file.txt").pipe(process.stdout);

Warning: Synchronous operations block the entire Node.js process. Use async alternatives or streams for I/O operations.

⚠️ Memory Leaks

// ❌ Bad: Event listeners not removed
const emitter = new EventEmitter();
emitter.on("data", handler);
// Listener stays in memory
// βœ… Good: Remove listeners
emitter.removeListener("data", handler);
// or
emitter.removeAllListeners();
// ❌ Bad: Closures holding references
function createHandler() {
const largeData = new Array(1000000).fill(0);
return () => {
// largeData stays in memory
};
}
// βœ… Good: Clear references
function createHandler() {
const largeData = new Array(1000000).fill(0);
return () => {
// Use data
largeData = null; // Clear reference
};
}

⚠️ Unhandled Promise Rejections

// ❌ Bad: Unhandled rejection
async function fetchData() {
const data = await api.getData(); // May reject
return data;
}
fetchData(); // No error handling
// βœ… Good: Handle errors
async function fetchData() {
try {
const data = await api.getData();
return data;
} catch (error) {
logger.error(error);
throw error;
}
}
// βœ… Good: Global handler
process.on("unhandledRejection", (reason, promise) => {
logger.error("Unhandled rejection:", reason);
});

⚠️ Callback Hell

// ❌ Bad: Nested callbacks
fs.readFile("file1.txt", (err, data1) => {
fs.readFile("file2.txt", (err, data2) => {
fs.readFile("file3.txt", (err, data3) => {
// Deep nesting
});
});
});
// βœ… Good: Use async/await
async function readFiles() {
const data1 = await fs.promises.readFile("file1.txt");
const data2 = await fs.promises.readFile("file2.txt");
const data3 = await fs.promises.readFile("file3.txt");
}
// βœ… Good: Use Promise.all for parallel
const [data1, data2, data3] = await Promise.all([
fs.promises.readFile("file1.txt"),
fs.promises.readFile("file2.txt"),
fs.promises.readFile("file3.txt"),
]);

⚠️ Error in Callbacks

// ❌ Bad: Throwing in callback
fs.readFile("file.txt", (err, data) => {
if (err) throw err; // May not be caught
});
// βœ… Good: Handle in callback
fs.readFile("file.txt", (err, data) => {
if (err) {
console.error(err);
return;
}
// Process data
});
// βœ… Good: Use promises/async
try {
const data = await fs.promises.readFile("file.txt");
} catch (err) {
console.error(err);
}

⚠️ Mixing Callbacks and Promises

// ❌ Bad: Mixing styles
function fetchData(callback) {
return fetch("api/data") // Returns promise
.then((data) => callback(null, data)) // But uses callback
.catch(callback);
}
// βœ… Good: Use one style
// Promise style
async function fetchData() {
return await fetch("api/data");
}
// Callback style
function fetchData(callback) {
fetch("api/data")
.then((data) => callback(null, data))
.catch((err) => callback(err));
}