Node.js Cheat Sheet for AI Prompting
Node.js Cheat Sheet for AI Prompting
Your complete quick reference for Node.js concepts and — most importantly — prompts to get the best results from AI coding tools. Bookmark this page!
npm Commands
# Project setup npm init -y # Create a new project with defaults npm install # Install all dependencies from package.json npm install express dotenv # Install specific packages npm install -D typescript # Install as dev dependency npm uninstall express # Remove a package # Running scripts npm start # Run the "start" script npm test # Run the "test" script npm run dev # Run a custom script npm run build # Build the project # Utility npx create-next-app@latest # Run a package without installing npx ts-node script.ts # Run TypeScript directly npm outdated # Check for outdated packages npm update # Update packages to latest allowed versions
File System Operations
import fs from "fs/promises"; import path from "path"; // Read a file const content = await fs.readFile("data.txt", "utf-8"); // Read and parse JSON const data = JSON.parse(await fs.readFile("data.json", "utf-8")); // Write a file await fs.writeFile("output.txt", "Hello!"); // Write JSON (pretty-printed) await fs.writeFile("out.json", JSON.stringify(data, null, 2)); // Create a directory (recursive = create parent dirs too) await fs.mkdir("output/subfolder", { recursive: true }); // List files in a directory const files = await fs.readdir("./data"); // Check if file exists import fsSync from "fs"; const exists = fsSync.existsSync("config.json"); // Delete a file await fs.unlink("temp.txt"); // Copy a file await fs.copyFile("source.txt", "backup.txt"); // Build cross-platform paths const filePath = path.join("data", "users", "profile.json"); const absolute = path.resolve("data", "file.txt");
Express Patterns
import express from "express"; import cors from "cors"; const app = express(); app.use(cors()); app.use(express.json()); // GET — read data app.get("/api/items", async (req, res) => { const items = await db.getAll(); res.json(items); }); // GET with URL params app.get("/api/items/:id", async (req, res) => { const item = await db.getById(req.params.id); if (!item) return res.status(404).json({ error: "Not found" }); res.json(item); }); // GET with query params (/api/search?q=hello&page=2) app.get("/api/search", async (req, res) => { const { q, page = "1" } = req.query; const results = await search(q, parseInt(page)); res.json(results); }); // POST — create data app.post("/api/items", async (req, res) => { const { name, description } = req.body; const item = await db.create({ name, description }); res.status(201).json(item); }); // PUT — update data app.put("/api/items/:id", async (req, res) => { const item = await db.update(req.params.id, req.body); res.json(item); }); // DELETE — remove data app.delete("/api/items/:id", async (req, res) => { await db.delete(req.params.id); res.status(204).send(); }); // Middleware const requireAuth = (req, res, next) => { if (!req.headers.authorization) { return res.status(401).json({ error: "Unauthorized" }); } next(); }; app.get("/api/protected", requireAuth, (req, res) => { res.json({ message: "Authenticated!" }); }); // Start server app.listen(3000, () => console.log("Running on port 3000"));
Async Patterns
// Basic async/await async function getData() { const response = await fetch("https://api.example.com/data"); const data = await response.json(); return data; } // Error handling async function safeFetch(url: string) { try { const response = await fetch(url); if (!response.ok) throw new Error(`HTTP ${response.status}`); return await response.json(); } catch (error) { console.error("Fetch failed:", error.message); return null; } } // Parallel operations const [users, posts, comments] = await Promise.all([ fetchUsers(), fetchPosts(), fetchComments(), ]); // Wait with timeout const timeout = (ms: number) => new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), ms) ); const result = await Promise.race([ fetchData(), timeout(5000), // Fail if it takes more than 5 seconds ]); // Process items one at a time for (const item of items) { await processItem(item); } // Process items in parallel (be careful with rate limits) await Promise.all(items.map((item) => processItem(item)));
Environment Variable Patterns
// Load .env file (do this first!) import dotenv from "dotenv"; dotenv.config(); // Read variables const apiKey = process.env.OPENAI_API_KEY; const port = process.env.PORT || "3000"; const isDev = process.env.NODE_ENV === "development"; // Validate required variables function requireEnv(name: string): string { const value = process.env[name]; if (!value) { throw new Error(`Missing required environment variable: ${name}`); } return value; } const dbUrl = requireEnv("DATABASE_URL"); const secret = requireEnv("JWT_SECRET");
# .env file format OPENAI_API_KEY=sk-abc123... DATABASE_URL=postgresql://user:pass@localhost:5432/mydb PORT=3000 NODE_ENV=development
Modules and Imports
// npm packages (no path prefix) import express from "express"; import { OpenAI } from "openai"; // Local files (start with ./ or ../) import { helper } from "./utils"; import { User } from "../types/User"; // Node.js built-in modules import fs from "fs/promises"; import path from "path"; import http from "http"; // Named exports export function add(a: number, b: number) { return a + b; } export const PI = 3.14159; // Default export export default class Database { /* ... */ } // Type-only imports (TypeScript) import type { User } from "./types";
Common package.json Scripts
{ "scripts": { "start": "node dist/index.js", "dev": "nodemon src/index.ts", "build": "tsc", "test": "jest", "lint": "eslint src/", "seed": "ts-node scripts/seed.ts", "clean": "rm -rf dist", "typecheck": "tsc --noEmit" } }
AI Prompts by Category
Project Setup
- "Create a new Node.js project with TypeScript, Express, and dotenv. Include the folder structure and all config files (tsconfig, package.json)."
- "Set up a Node.js project that connects to Firebase Firestore. Include environment variable handling and TypeScript types."
- "Initialize a Node.js project with ESLint, Prettier, and TypeScript configured."
Building APIs
- "Build a REST API with Express for a [blog / task manager / inventory system]. Include all CRUD endpoints with proper error handling."
- "Create an API endpoint that receives a user's question, sends it to the Claude API, and returns the response."
- "Add authentication middleware to my Express API using JWT tokens."
- "Build an Express API with input validation using Zod. Validate request bodies before processing."
Working with Files
- "Write a Node.js script that reads all .json files from a directory, merges them into one array, and saves the result."
- "Create a script that watches a folder for new files and processes them automatically."
- "Build a CLI tool that takes a CSV file as input and converts it to JSON."
Database Operations
- "Create a Firestore service with functions to create, read, update, and delete documents in the [collection name] collection."
- "Write a seed script that reads data from a JSON file and inserts it into [database]."
- "Build a data migration script that transforms documents in a Firestore collection."
Async and APIs
- "I'm making three sequential API calls that are independent. Refactor them to run in parallel with Promise.all."
- "Add retry logic with exponential backoff to this API call."
- "Create a rate-limited queue that processes API calls with a maximum of 5 concurrent requests."
Scripts and Automation
- "Create a Node.js script that calls the [API name] API and saves the results to a JSON file."
- "Build a script that processes a large dataset in batches of 100 items with progress logging."
- "Write a deployment script that builds the project, runs tests, and logs the results."
Debugging
- "I'm getting 'Cannot find module' when importing a file. Here's my file structure: [paste]. What's wrong?"
- "My async function returns a Promise instead of the actual value. Here's the code: [paste]."
- "My Express server crashes with 'EADDRINUSE'. What does this mean and how do I fix it?"
- "I'm getting 'ERR_MODULE_NOT_FOUND' errors. How do I configure my project for ES Modules?"
Performance
- "My API endpoint is slow because it makes 10 sequential database calls. Help me optimize it."
- "Add caching to my Express API using node-cache. Cache GET responses for 5 minutes."
- "My Node.js process runs out of memory processing a large file. How do I use streams instead?"
Quick Debugging Reference
| Error | Meaning | Fix |
|---|---|---|
Cannot find module | Wrong import path or missing package | Check path or run npm install |
EADDRINUSE | Port is already in use | Kill the other process or use a different port |
ENOENT | File or directory not found | Check the file path exists |
ERR_MODULE_NOT_FOUND | ES Module import resolution failed | Add file extension or check "type": "module" in package.json |
SyntaxError: Cannot use import | Using ESM syntax in CommonJS | Add "type": "module" or use require() |
UnhandledPromiseRejection | Missing error handling on a Promise | Add .catch() or try/catch |
TypeError: X is not a function | Wrong import or variable type | Check your imports and variable types |
The Complete Beginner Workflow
When working with AI on a Node.js project:
1. DESCRIBE what you want to build (be specific about the stack)
2. READ the generated code — look at package.json and entry files first
3. RUN npm install to install dependencies
4. RUN the project with npm run dev
5. TEST the endpoints or scripts
6. ITERATE — tell the AI what to change or fix
The key insight: You don't need to memorize everything in this cheat sheet. You need to:
- Recognize the patterns when AI generates them
- Describe what you want clearly so AI generates the right code
- Debug common issues using the error reference above
- Know the right follow-up prompts when something doesn't work
Remember: Every experienced Node.js developer started by running
node hello.js. With AI tools like Claude Code, you can build real backend applications while you learn. Use these prompts, experiment with the patterns, and don't be afraid to ask your AI to explain anything you don't understand.
Happy building!