Node.js Core Modules Cheat Sheet
Quick reference guide for Node.js core modules: fs/promises, path, stream, http, events, child_process, and Buffer.
Node.js is an open-source, cross-platform JavaScript runtime environment. Its built-in standard modules allow server-side I/O, file handling, HTTP networking, and process management.
File System (`fs/promises`)
The fs/promises module provides asynchronous file operations returning Promises.
import fs from "node:fs/promises";
import path from "node:path";
// Read and parse JSON file
async function loadConfig(filePath: string) {
const absolutePath = path.resolve(filePath);
const rawData = await fs.readFile(absolutePath, "utf-8");
return JSON.parse(rawData);
}
// Write content safely
async function saveLog(filePath: string, message: string) {
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.appendFile(filePath, `${new Date().toISOString()} - ${message}\n`);
}
Path Operations (`node:path`)
| Method | Output Example | Description |
|---|---|---|
path.join('/a', 'b', 'c.txt') | /a/b/c.txt | Join path segments with OS separator |
path.resolve('dir', 'file.js') | /abs/cwd/dir/file.js | Resolve to absolute path from CWD |
path.extname('app.config.json') | .json | Extract extension including dot |
path.basename('/a/b/file.txt') | file.txt | Extract filename portion |
path.dirname('/a/b/file.txt') | /a/b | Extract directory path portion |
HTTP Server (`node:http`)
Create a lightweight native HTTP server without third-party dependencies.
import http from "node:http";
const server = http.createServer((req, res) => {
if (req.url === "/api/health" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "ok", timestamp: Date.now() }));
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
});
server.listen(3000, () => {
console.log("Server listening on http://localhost:3000");
});
EventEmitter (`node:events`)
import { EventEmitter } from "node:events";
class UserNotifier extends EventEmitter {}
const notifier = new UserNotifier();
// Subscribe to event
notifier.on("userJoined", (user: { name: string }) => {
console.log(`User registered: ${user.name}`);
});
// Emit event
notifier.emit("userJoined", { name: "Alice" });
Buffer & Binary Data (`node:buffer`)
| Operation | Code Snippet | Purpose |
|---|---|---|
| Create from String | Buffer.from("Hello", "utf-8") | Convert text to raw byte buffer |
| Create from Base64 | Buffer.from("aGVsbG8=", "base64") | Decode base64 binary buffer |
| Output Base64 | buf.toString("base64") | Encode buffer into base64 string |
| Buffer Length | buf.length | Byte count of the buffer |
Common Pitfalls & Tips
[!WARNING] Synchronous methods like
fs.readFileSync()block the entire single-threaded Event Loop! Always preferfs/promisesor callback equivalents in server environments.
[!TIP] Use the explicit
node:prefix when importing core modules (e.g.,import fs from 'node:fs/promises') to prevent conflicts with npm packages and improve load performance.