How to Stream CLI Output with a Progress Bar
Write a progress bar to stderr with a carriage return so it updates in place and does not pollute stdout when the output is piped to a file.
Step-by-step guides and in-depth articles to level up your skills.
Page 4 of 9
Write a progress bar to stderr with a carriage return so it updates in place and does not pollute stdout when the output is piped to a file.
Parse a JSON stream incrementally so the UI renders the first items before the full response arrives and the user sees progress not a spinner.
Pipe a multipart upload straight to storage with Node streams so a 2 GB file never sits in memory and the server stays responsive under load.
Add the new credential, switch the app, then remove the old so a password change does not break in-flight connections.
Share one Zod schema between client and server so the validation rules never drift and a change in one place updates both sides.
Capture stdout and stderr in a test, run the command, and snapshot the output so a change to the format is caught in review.
Extract validation logic from the component, test it with plain data, and assert the error shape so UI and logic tests stay separate.
Track type-2 changes with valid-from and valid-to so a dimension row preserves history and a query can point-in-time the join.
Generate a presigned S3 URL so the browser uploads directly to the bucket and your server never proxies the bytes or pays for the bandwidth.
Hold fetch state in a context with a reducer so deep components read loading and error without prop drilling or a global store.
Use Zod array schemas with object elements to validate dynamic lists where each row has its own errors and the UI renders them inline.
Compute a checksum on the source and verify on the destination so a truncated or corrupted transfer is caught before it is committed.
Make a field required only when another field has a specific value using Zod superRefine so the rule lives in the schema not the UI.
Parse and validate config before the app serves so a bad key crashes the boot, not the first request that needs it.
Implement the Luhn checksum to validate credit card numbers client-side, strip spaces, and reject obviously invalid input early.
Define a shared schema for the data a service emits and the consumer expects so a change that breaks the contract is caught in CI.
Write SQL assertions that check invariants and fail the load on violation so a broken batch is stopped before it reaches the report.
Parse, normalize, and compare dates across timezones with a library so a midnight UTC date does not become the wrong day locally.
Store in UTC and convert at the boundary so a query for today returns the same rows regardless of the session timezone.
Cascade the options of a second select from the value of the first, validate the combination, and clear the dependent field on change.
Validate select and radio inputs against an enum so a tampered POST with an out-of-range value is rejected at the boundary, not in the UI.
Sniff the magic bytes and reject if they do not match the claimed type so a renamed executable does not pass as an image.
Check file size, type, and name in the browser before the upload starts so wasted requests never leave the client.
Parse and validate international phone numbers with libphonenumber, handle country codes, and reject malformed input at the boundary.
Parse with libphonenumber, normalize to E.164, and reject invalid so a phone field is a real number not a free-text string.
Check the issuer, audience, expiry, and required claims on every token so a token from the wrong audience or a missing role is rejected at the boundary.
Parse multipart form data with a streaming parser that enforces boundary and part limits so a malformed request cannot exhaust the server.
Compose Zod object schemas to validate deeply nested data and collect every error path so the user sees all problems at once.
Compose AJV custom keywords to validate nested JSON, report every issue at once, and test the error shape your UI renders.
Fetch the discovery keys, verify the signature and claims of the ID token, and extract the user identity so a server trusts the OIDC flow.
Choose when validation fires so blur gives early feedback without blocking typing and submit gives the full check before the request leaves.
Check the Origin header against an allowlist so a cross-site request from a disallowed origin is rejected before it runs.
Score password strength with a rule set for length, character classes, and entropy, show feedback live, and reject weak passwords at submit.
Check that a foreign key exists before accepting a write so a service does not store a reference to a resource another service never had.
Validate every input at the entry point with a schema so the handler receives typed data and never re-checks what the boundary already checked.
Check the Content-Type and the actual bytes server-side so a client lying about the type is rejected before the file is stored or served.
Add field and model validators in Pydantic v2 for rules the types cannot express so validation lives in the schema not the handler.
Validate form fields against the server without blocking typing, debouncing requests and cancelling stale ones with AbortController.
Isolate pools of connections by tenant or feature so one slow tenant cannot exhaust the shared pool and take down everyone.
Open the circuit after failures, probe with one request in half-open, and close only if the probe succeeds so a flapping dependency does not get flooded.
Layer configuration from defaults, file, environment, and flags with explicit precedence so users can override at the right level.
Add color to CLI output only when stdout is a TTY, respecting NO_COLOR and force-color so pipes and logs stay clean.
Show a progress bar for long tasks by writing carriage returns to the same line, and hide it when stdout is not a TTY.
For each step that mutates state, define an inverse that undoes it, so a failed multi-step flow can roll back to a consistent state.
Show and hide form fields based on other field values, keeping hidden fields out of validation and the submitted payload.
Lock down inline scripts with per-request nonces and strict-dynamic so injected scripts without the nonce cannot run, even with DOM bugs.
Store state as a sequence of events and rebuild by replaying, with periodic snapshots so replay does not read the entire history.
Achieve exactly-once semantics by combining at-least-once delivery with idempotent processing keyed by message ID, not true once delivery.
Roll out a feature to a percentage of users with a sticky bucket and a kill switch, so you can ramp up or abort without a deploy.
Serve a reduced experience when a dependency is down by falling back to cached data or a default, never showing an error page for a non-critical feature.
Ensure a tenant token can never access another tenant data by binding the tenant ID into the token and enforcing it at the query layer.
Secure public-client authorization with PKCE by generating a code verifier, sending its challenge, and validating on token exchange.
Detect concurrent modifications with a version number or vector clock, rejecting stale writes so the last writer does not silently clobber earlier work.
Update the UI immediately before the server confirms, rolling back on error so the app feels fast without showing stale data.
Set Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy to isolate your origin from cross-origin documents and enable crossOriginIsolated.
Use signals to make data fetches reactive so dependent computations update automatically when the source changes, without manual subscriptions.
Save form drafts automatically as the user types, debouncing writes, resolving conflicts, and showing a subtle save indicator.
Upload large files resumably with the tus protocol, handling interruptions, PATCH continuation, and upload-creation once per file.
Retry transient failures with exponential backoff plus random jitter and a max attempt cap to avoid thundering herds.
Authorize requests by mapping user roles to permissions with a hierarchy, checking both the role and the specific action before executing.
Coordinate a multi-step transaction across services with compensating actions on failure, so a partial failure does not leave the system inconsistent.
Add a cryptographic hash to external script and style tags so a compromised CDN cannot inject modified code into your page.
Layer per-tenant config on top of the base so one instance serves many tenants with isolated settings, without a config per instance.
Issue short access tokens and rotating refresh tokens, detecting reuse to revoke the whole session on replay.
Require all DOM XSS sinks like innerHTML to receive a TrustedTypes policy, so raw strings cannot reach them even with a bug.
Use opaque cursor pagination instead of offset so inserts and deletes during paging do not skip or duplicate rows.
Set CSP frame-ancestors to none or self so your page cannot be framed by an attacker who overlays invisible buttons on your content.
Use a conditional write that only applies if the current value matches the expected, so a concurrent update cannot be silently lost.
Validate the next parameter against an allowlist before redirecting, so an attacker cannot craft a link that bounces users to a malicious site.
Handle uploads larger than memory by piping the request stream through transforms, never buffering the whole file.
When a downstream service is down, enqueue the work in a durable queue and process it on recovery instead of failing the user request.
Show real upload progress by reading the request body stream, updating a progress bar without XMLHttpRequest.
Encode data on output, not input, and use a context-aware encoder so values inserted into HTML, attributes, or script contexts are all safe.
Strip dangerous HTML from rich-text input using DOMPurify with an allowlist, preventing XSS while preserving safe formatting.
Validate and restrict outbound URLs from user input to prevent server-side request forgery to internal metadata and admin endpoints.
Store JWT in an httpOnly cookie with SameSite=strict and a double-submit token for stateless CSRF defense, not in localStorage.
Choose between httpOnly cookie and in-memory storage for JWTs, understanding the XSS and CSRF tradeoffs of each location.
Deduplicate uploads by their SHA-256 hash, storing each unique blob once and referencing it by digest to save space.
Parse a large JSON stream incrementally as chunks arrive, so the UI can render the first items before the whole response downloads.
Resolve concurrent edits to the same record with last-write-wins per field or a CRDT merge, so collaboration does not silently drop changes.
Test CLI output by capturing stdout in a child process and snapshotting it, so refactors do not silently change the user-facing text.
Let the browser upload straight to S3 using a short-lived presigned URL, keeping your server out of the data path and saving bandwidth.
Validate checkbox groups for minimum selection and radio groups for required choice, mapping native constraints to clear messages.
Parse and validate the entire config with a schema before the app starts, so a misconfigured instance refuses to boot instead of failing at runtime.
Parse and validate deeply nested form payloads with Zod schemas, surfacing field-level errors without losing the original input shape.
Collect per-field and form-level errors into one structure, order them by severity, and render an accessible error summary that links to each field.
Cancel an in-flight upload with AbortController, clean up the partial server-side artifact, and refund the UI to idle without leaked listeners.
Split a large file into chunks, upload each with its own retry, and resume from the last confirmed chunk after a network drop without restarting.
Make fields required based on another field value using discriminated unions or refine, so the schema encodes the dependency instead of the UI.
Validate rules that span multiple fields like password confirm, date ranges, and conditional billing with a single refine over the whole form.
Debounce async field checks so the server is hit once after typing settles, cancel stale requests, and keep the submit button responsive during checks.
Build an accessible drag-and-drop zone that also works with keyboard and click, validates dropped files, and avoids the common dropoutside bug.
Sniff the real file type from magic bytes instead of trusting the extension or Content-Type, and reject mismatches before storing the upload.
Implement an atomic, sharded counter in Redis with INCR, CRDT merge for partitions, and eventual consistency for global aggregation.
Design an in-process feature flag service with rules, gradual rollouts, and safe overrides that degrade gracefully when the flag store is unavailable.
Deliver webhooks with exponential backoff, jitter, dead-letter queues, and idempotency to handle endpoint failures without losing events.
Version an API by embedding the version in the URL path, with backward-compatible defaults, deprecation headers, and sunset tracking.
Route read queries to replica databases and writes to the primary, with health checks and fallback when replicas lag or fail.
Let clients select specific fields via a fields query parameter, reducing payload size and improving latency for mobile and edge clients.
Authorize every GraphQL resolver with field-level checks, depth limiting, and query cost analysis to prevent data leaks and expensive queries.