#nodejs
62 snippets tagged with #nodejs
Node.js Worker Threads for Parallel Processing
Use Worker Threads to run CPU-intensive tasks in parallel without blocking the event loop.
Best for: CPU-intensive data processing without blocking
Node.js Stream Pipeline with Transform
Build efficient data processing pipelines using Node.js streams for large file handling.
Best for: Processing large CSV files without loading into memory
TypeScript Typed Event Emitter
Create type-safe event emitters in Node.js with full TypeScript support and autocomplete.
Best for: Type-safe pub/sub communication between modules
Node.js Graceful Shutdown Handler
Implement graceful shutdown to properly close connections and finish requests before exit.
Best for: Production Node.js server reliability
Node.js Crypto Utility Functions
Common cryptographic operations: hashing, HMAC, encryption, random tokens, and password hashing.
Best for: Secure password storage and verification
Node.js Recursive File Watcher
Watch files and directories for changes with debouncing and glob pattern filtering.
Best for: Custom hot-reload during development
Node.js Cluster Mode for Scaling
Scale Node.js across CPU cores using the cluster module with automatic worker respawning.
Best for: Utilizing all CPU cores for HTTP servers
Request Validation Schema Builder
Build a lightweight request validation layer with type inference for API endpoints.
Best for: API request body validation
Node.js In-Memory Task Queue
A simple in-memory task queue with concurrency control, retries, and priority support.
Best for: Rate-limited API call processing
Node.js Token Bucket Rate Limiter
Implement an in-memory token bucket rate limiter for controlling API request throughput.
Best for: Protecting APIs from abuse and DDoS
Read and Write JSON Files
Read, parse, modify, and write JSON files with proper error handling using Node.js fs module.
Best for: Configuration file management
Cross-Platform Path Operations
Use Node.js path module for cross-platform file path manipulation, resolution, and normalization.
Best for: Cross-platform file path handling
Child Process: exec and spawn
Execute shell commands and spawn processes with exec, execFile, spawn, and fork in Node.js.
Best for: Running shell commands from Node.js
Native HTTP Server
Create a lightweight HTTP server using Node.js built-in http module with routing and JSON responses.
Best for: Lightweight API server without frameworks
Event Loop and Timers
Understand Node.js event loop phases with setTimeout, setInterval, setImmediate, and process.nextTick.
Best for: Understanding async execution order
Streams: Readable, Writable, Transform
Build custom readable, writable, and transform streams for efficient data processing in Node.js.
Best for: Processing large files without loading into memory
Custom Error Classes
Create typed custom error classes with HTTP status codes, error codes, and structured error handling.
Best for: Structured API error responses
Middleware Pattern and Composition
Implement the middleware pattern for composable request processing with next() and error handling.
Best for: Request processing pipelines
Promise Concurrency Patterns
Master Promise.all, allSettled, race, any — parallel execution with error handling and timeouts.
Best for: Parallel API calls with error handling
Directory Operations with fs
Create, read, copy, and remove directories recursively using Node.js fs/promises.
Best for: Build tool directory management
Compression with zlib
Compress and decompress data using gzip, deflate, and brotli with Node.js built-in zlib module.
Best for: API response compression
URL and Query String Parsing
Parse, construct, and manipulate URLs and query strings using the Node.js URL and URLSearchParams API.
Best for: API URL construction
Process Signals and Environment
Handle process signals, environment variables, exit codes, and unhandled errors in Node.js.
Best for: Graceful server shutdown
Buffer and Binary Data
Work with binary data using Node.js Buffer: create, convert, slice, encode/decode, and compare.
Best for: Binary protocol implementation
Native Test Runner and Assert
Write tests using Node.js built-in test runner and assert module — no external dependencies needed.
Best for: Unit testing without external packages
Crypto Hashing and HMAC
Generate secure hashes, HMACs, and checksums using Node.js built-in crypto module.
Best for: Webhook signature verification
AbortController for Cancellation
Cancel async operations with AbortController: fetch requests, timers, streams, and custom operations.
Best for: Request timeout handling
Performance Measurement
Measure execution time with performance.now(), Performance API marks, measures, and PerformanceObserver.
Best for: Function execution profiling
Typed Event Emitter Class
Build a type-safe event emitter with TypeScript generics for strongly-typed event handling.
Best for: Type-safe event-driven architecture
Interactive CLI with Readline
Build interactive command-line interfaces using Node.js readline with prompts, history, and auto-completion.
Best for: Building simple CLI tools
DNS Lookup and Resolution
Perform DNS lookups, resolve hostnames to IP addresses, and query DNS records using Node.js dns module.
Best for: Network diagnostics tools
System Information with OS Module
Retrieve system information including CPU, memory, network interfaces, and platform details using os module.
Best for: Server health dashboards
HTTP/2 Server with Stream Push
Create an HTTP/2 server with server push, multiplexed streams, and TLS configuration in Node.js.
Best for: High-performance web servers
Async Iterators for Stream Processing
Process streams and async data sources with for-await-of loops and custom async iterators in Node.js.
Best for: Paginated API data consumption
Cluster Worker Pool Pattern
Distribute CPU-intensive tasks across worker processes with automatic restart and load balancing.
Best for: Multi-core CPU utilization
TCP Server and Client with Net Module
Build TCP server and client pairs using Node.js net module with connection pooling and message framing.
Best for: Custom protocol implementation
Event-Driven Architecture Pattern
Build loosely coupled systems with typed event bus, async event handlers, and domain event patterns.
Best for: Microservice communication
JavaScript Proxy Handler Pattern
Use Proxy and Reflect to create observable objects, validation layers, and dynamic API clients.
Best for: Observable state management
Schema Validation with Zod-like Patterns
Build a minimal schema validation library inspired by Zod using TypeScript type inference.
Best for: API request validation
Express Error Handling Middleware
Centralized error handling in Express with custom error classes, async wrapper, and structured responses.
Best for: API error standardization
Dependency Injection Container
Build a lightweight DI container with singleton and transient scopes for testable Node.js applications.
Best for: Testable application architecture
Semaphore for Concurrency Limiting
Control concurrent async operations with a semaphore pattern: rate limiting, connection pooling, and batch processing.
Best for: API rate limiting
In-Memory Caching with LRU Strategy
Implement LRU cache with TTL expiration, size limits, and cache-aside pattern for Node.js applications.
Best for: API response caching
Retry with Exponential Backoff
Retry failed async operations with exponential backoff, jitter, and configurable retry conditions.
Best for: API call resilience
Promise Pool for Batch Processing
Process large arrays with controlled concurrency using a promise pool pattern with progress tracking.
Best for: Bulk API requests
Type-Safe Configuration Loader
Load and validate configuration from environment variables with type coercion and required field checks.
Best for: Application configuration management
Structured JSON Logger
Build a structured logger with log levels, context, child loggers, and JSON output for Node.js services.
Best for: Application logging for production
Middleware Chain Pattern
Implement the middleware/pipeline pattern for composable request processing without Express.
Best for: Custom HTTP framework
Fastify Server Setup
Create a high-performance Fastify server with schema validation, plugins, and typed routes.
Best for: High-performance REST APIs
CORS Configuration Middleware
Configure Cross-Origin Resource Sharing with origin allowlists, credentials, and preflight handling.
Best for: API CORS configuration
Secure Cookie and Session Management
Handle HTTP cookies with signing, encryption, and session management using secure defaults.
Best for: Authentication session handling
GraphQL Server with Type Definitions
Build a GraphQL API server with type definitions, resolvers, and query/mutation support.
Best for: GraphQL API development
Health Check Endpoint Pattern
Implement comprehensive health checks with dependency status, uptime, and readiness probes.
Best for: Kubernetes liveness probes
Webhook Handler with Signature Verification
Process incoming webhooks with HMAC signature verification, replay protection, and idempotency.
Best for: GitHub/Stripe webhook processing
Cursor-Based Pagination API
Implement cursor-based pagination with forward/backward navigation, consistent ordering, and link headers.
Best for: REST API pagination
API Versioning Strategy
Implement API versioning with URL path, header-based, and content negotiation strategies.
Best for: API backward compatibility
Debug with Inspector Protocol
Programmatic debugging with Node.js inspector module for heap snapshots, CPU profiling, and breakpoints.
Best for: Production performance profiling
ESM and CJS Module Interop
Handle ECMAScript module and CommonJS interop with dynamic imports, conditional exports, and dual packages.
Best for: Library dual packaging
Application Metrics Collection
Collect and expose application metrics like request counts, latency histograms, and custom gauges.
Best for: Prometheus metrics endpoint
Pub/Sub Messaging Pattern
Implement publish/subscribe messaging with topics, filtered subscriptions, and message replay.
Best for: In-process event messaging
PM2 Process Manager Configuration
PM2 ecosystem file for managing Node.js processes with clustering, log rotation, and auto-restart.
Best for: Running Node.js in production with clustering
GitHub Actions — Node.js CI Pipeline
Complete CI workflow for Node.js: install, lint, test, build on every push and PR with caching.
Best for: Automated testing on every push and PR