#nodejs

62 snippets tagged with #nodejs

typescriptadvanced

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

#nodejs#worker-threads
typescriptintermediate

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

#nodejs#streams
typescriptintermediate

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

#nodejs#events
typescriptintermediate

Node.js Graceful Shutdown Handler

Implement graceful shutdown to properly close connections and finish requests before exit.

Best for: Production Node.js server reliability

#nodejs#shutdown
typescriptintermediate

Node.js Crypto Utility Functions

Common cryptographic operations: hashing, HMAC, encryption, random tokens, and password hashing.

Best for: Secure password storage and verification

#nodejs#crypto
typescriptintermediate

Node.js Recursive File Watcher

Watch files and directories for changes with debouncing and glob pattern filtering.

Best for: Custom hot-reload during development

#nodejs#file-system
typescriptadvanced

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

#nodejs#cluster
typescriptintermediate

Request Validation Schema Builder

Build a lightweight request validation layer with type inference for API endpoints.

Best for: API request body validation

#nodejs#validation
typescriptadvanced

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

#nodejs#queue
typescriptintermediate

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

#nodejs#rate-limiting
typescriptbeginner

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

#nodejs#json
typescriptbeginner

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

#nodejs#path
typescriptintermediate

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

#nodejs#child-process
typescriptbeginner

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

#nodejs#http
typescriptintermediate

Event Loop and Timers

Understand Node.js event loop phases with setTimeout, setInterval, setImmediate, and process.nextTick.

Best for: Understanding async execution order

#nodejs#event-loop
typescriptadvanced

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

#nodejs#streams
typescriptbeginner

Custom Error Classes

Create typed custom error classes with HTTP status codes, error codes, and structured error handling.

Best for: Structured API error responses

#nodejs#error
typescriptintermediate

Middleware Pattern and Composition

Implement the middleware pattern for composable request processing with next() and error handling.

Best for: Request processing pipelines

#nodejs#middleware
typescriptintermediate

Promise Concurrency Patterns

Master Promise.all, allSettled, race, any — parallel execution with error handling and timeouts.

Best for: Parallel API calls with error handling

#nodejs#promise
typescriptbeginner

Directory Operations with fs

Create, read, copy, and remove directories recursively using Node.js fs/promises.

Best for: Build tool directory management

#nodejs#fs
typescriptintermediate

Compression with zlib

Compress and decompress data using gzip, deflate, and brotli with Node.js built-in zlib module.

Best for: API response compression

#nodejs#zlib
typescriptbeginner

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

#nodejs#url
typescriptintermediate

Process Signals and Environment

Handle process signals, environment variables, exit codes, and unhandled errors in Node.js.

Best for: Graceful server shutdown

#nodejs#process
typescriptintermediate

Buffer and Binary Data

Work with binary data using Node.js Buffer: create, convert, slice, encode/decode, and compare.

Best for: Binary protocol implementation

#nodejs#buffer
typescriptbeginner

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

#nodejs#testing
typescriptintermediate

Crypto Hashing and HMAC

Generate secure hashes, HMACs, and checksums using Node.js built-in crypto module.

Best for: Webhook signature verification

#nodejs#crypto
typescriptadvanced

AbortController for Cancellation

Cancel async operations with AbortController: fetch requests, timers, streams, and custom operations.

Best for: Request timeout handling

#nodejs#abort
typescriptadvanced

Performance Measurement

Measure execution time with performance.now(), Performance API marks, measures, and PerformanceObserver.

Best for: Function execution profiling

#nodejs#performance
typescriptadvanced

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

#nodejs#events
typescriptbeginner

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

#nodejs#readline
typescriptbeginner

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

#nodejs#dns
typescriptbeginner

System Information with OS Module

Retrieve system information including CPU, memory, network interfaces, and platform details using os module.

Best for: Server health dashboards

#nodejs#os
typescriptadvanced

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

#nodejs#http2
typescriptadvanced

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

#nodejs#async-iterator
typescriptadvanced

Cluster Worker Pool Pattern

Distribute CPU-intensive tasks across worker processes with automatic restart and load balancing.

Best for: Multi-core CPU utilization

#nodejs#cluster
typescriptadvanced

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

#nodejs#tcp
typescriptintermediate

Event-Driven Architecture Pattern

Build loosely coupled systems with typed event bus, async event handlers, and domain event patterns.

Best for: Microservice communication

#nodejs#events
typescriptadvanced

JavaScript Proxy Handler Pattern

Use Proxy and Reflect to create observable objects, validation layers, and dynamic API clients.

Best for: Observable state management

#nodejs#proxy
typescriptintermediate

Schema Validation with Zod-like Patterns

Build a minimal schema validation library inspired by Zod using TypeScript type inference.

Best for: API request validation

#nodejs#validation
typescriptintermediate

Express Error Handling Middleware

Centralized error handling in Express with custom error classes, async wrapper, and structured responses.

Best for: API error standardization

#nodejs#express
typescriptadvanced

Dependency Injection Container

Build a lightweight DI container with singleton and transient scopes for testable Node.js applications.

Best for: Testable application architecture

#nodejs#dependency-injection
typescriptintermediate

Semaphore for Concurrency Limiting

Control concurrent async operations with a semaphore pattern: rate limiting, connection pooling, and batch processing.

Best for: API rate limiting

#nodejs#concurrency
typescriptintermediate

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

#nodejs#caching
typescriptintermediate

Retry with Exponential Backoff

Retry failed async operations with exponential backoff, jitter, and configurable retry conditions.

Best for: API call resilience

#nodejs#retry
typescriptintermediate

Promise Pool for Batch Processing

Process large arrays with controlled concurrency using a promise pool pattern with progress tracking.

Best for: Bulk API requests

#nodejs#promise
typescriptbeginner

Type-Safe Configuration Loader

Load and validate configuration from environment variables with type coercion and required field checks.

Best for: Application configuration management

#nodejs#config
typescriptbeginner

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

#nodejs#logging
typescriptintermediate

Middleware Chain Pattern

Implement the middleware/pipeline pattern for composable request processing without Express.

Best for: Custom HTTP framework

#nodejs#middleware
typescriptbeginner

Fastify Server Setup

Create a high-performance Fastify server with schema validation, plugins, and typed routes.

Best for: High-performance REST APIs

#nodejs#fastify
typescriptbeginner

CORS Configuration Middleware

Configure Cross-Origin Resource Sharing with origin allowlists, credentials, and preflight handling.

Best for: API CORS configuration

#nodejs#cors
typescriptintermediate

Secure Cookie and Session Management

Handle HTTP cookies with signing, encryption, and session management using secure defaults.

Best for: Authentication session handling

#nodejs#cookies
typescriptadvanced

GraphQL Server with Type Definitions

Build a GraphQL API server with type definitions, resolvers, and query/mutation support.

Best for: GraphQL API development

#nodejs#graphql
typescriptbeginner

Health Check Endpoint Pattern

Implement comprehensive health checks with dependency status, uptime, and readiness probes.

Best for: Kubernetes liveness probes

#nodejs#health-check
typescriptintermediate

Webhook Handler with Signature Verification

Process incoming webhooks with HMAC signature verification, replay protection, and idempotency.

Best for: GitHub/Stripe webhook processing

#nodejs#webhook
typescriptintermediate

Cursor-Based Pagination API

Implement cursor-based pagination with forward/backward navigation, consistent ordering, and link headers.

Best for: REST API pagination

#nodejs#pagination
typescriptintermediate

API Versioning Strategy

Implement API versioning with URL path, header-based, and content negotiation strategies.

Best for: API backward compatibility

#nodejs#api
typescriptadvanced

Debug with Inspector Protocol

Programmatic debugging with Node.js inspector module for heap snapshots, CPU profiling, and breakpoints.

Best for: Production performance profiling

#nodejs#debugging
typescriptbeginner

ESM and CJS Module Interop

Handle ECMAScript module and CommonJS interop with dynamic imports, conditional exports, and dual packages.

Best for: Library dual packaging

#nodejs#esm
typescriptadvanced

Application Metrics Collection

Collect and expose application metrics like request counts, latency histograms, and custom gauges.

Best for: Prometheus metrics endpoint

#nodejs#monitoring
typescriptintermediate

Pub/Sub Messaging Pattern

Implement publish/subscribe messaging with topics, filtered subscriptions, and message replay.

Best for: In-process event messaging

#nodejs#pubsub
javascriptintermediate

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

#pm2#process-manager
yamlbeginner

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

#github-actions#ci-cd