Durable Writes With FileHandle Sync
Force file data to stable storage with FileHandle.sync, reopen with datasync for a metadata-free flush, and read the bytes back.
Page 2 of 9
Force file data to stable storage with FileHandle.sync, reopen with datasync for a metadata-free flush, and read the bytes back.
Write with flag 'wx' so an existing path fails with EEXIST instead of truncating, the one-time init and lockfile pattern.
Function declarations are callable before their definition line, while function expressions follow const rules and throw a ReferenceError if called early.
Read Function.prototype.length to get how many parameters are declared before the first default, so frameworks can read handler arity.
Score subsequence matches by how tightly the query characters cluster inside the target, ranking command palettes without any dependency.
getRootNode reports whether a node belongs to the document or a shadow root, letting widgets branch on containment without leaking closed trees.
A g-flag regex object carries lastIndex across exec and test calls, so reusing one literal skips matches until you reset it or use matchAll.
Start a backup replica after a short tail delay and race it against the primary, keeping the first answer so slow replicas stop dominating latency.
Serve JSON with node:http createServer alone: listen(0) takes a free ephemeral port and close releases the handle so the process exits.
img.decode() resolves once pixels are ready to paint, so awaiting it before insertion removes the half-decoded flash of a plain src swap.
Set element.inert on the page behind a modal so clicks, focus, and assistive tech skip it, restoring interactivity when the dialog closes.
Row updates that settle after their element was removed must check isConnected first, the cheap guard against writing into detached nodes.
Give plain .js files real types with @typedef, @property, @param, and @returns so editors and tsc --checkJS validate calls without any build step.
Read each value's original source text in the reviver so decimal literals like 19.99 survive as exact strings instead of rounded floats.
Turn keydown events into actions with a hotkey map; modifier keys join the combination and text inputs plus IME composition are skipped.
Keep one tail promise per key so same-key tasks serialize while different keys run concurrently; failures never poison the chain and idle keys clean up.
The first call starts one init promise that every caller shares, and a rejection clears it so the next call retries instead of failing forever.
Access a let or const binding before its declaration runs and the temporal dead zone throws a ReferenceError; var instead reads undefined from hoisting.
var declares one binding per loop so every callback sees the final value; let makes a fresh binding per iteration, the fix an IIFE once did by hand.
Map iteration is live: entries appended mid-loop get visited, entries deleted before being reached are skipped, and re-sets keep their position.
play() returns a promise whose rejection name explains the block: AbortError when pause lands first, NotAllowedError when autoplay policy wants a gesture.
The % operator keeps the dividend's sign, so backward steps yield negatives — the double-modulo idiom wraps any index back into range.
The m flag anchors ^ and $ at every line break while s lets dot cross newlines, together enabling per-line scanning of multi-line records.
Read Notification.permission without prompting, then call requestPermission inside a user gesture and branch on the resolved decision before showing a note.
Read navigator.onLine for a synchronous connectivity snapshot and subscribe to the online/offline events to pause work and resume queues.
Persist progress files in the origin-private file system: getDirectory, a writable handle, and estimate() quota reporting in one flow.
Normalize mixed line endings by splitting on /\r?\n/ and rejoining with os.EOL, so written files use the platform-native terminator.
Parse CLI input with util.parseArgs using tokens: true to locate the subcommand positional and route the rest of the argument stream per verb.
Turn a sorted sample into p50 or p99 with linear interpolation between neighboring ranks, matching how perf metrics summarize latency.
Check navigator.permissions.query({ name }) before using a gated API, branch on granted/denied/prompt, and listen for runtime state changes.
Build one running-total pass and a prefix array, then any i..j range sum is a single subtraction instead of another loop over the data.
Load .env configuration with process.loadEnvFile() and note the precedence rule: values already in the environment are never overridden.
Promise.all only reports final settlement; attaching a then hook to each task yields an incremental progress count without changing result order.
Use the :has() relational pseudo-class in querySelectorAll to select elements by their descendants, including negations like :not(:has(...)).
Iterate a file with readline.createInterface over a read stream, counting lines incrementally instead of loading the whole file into memory.
RegExp.escape quotes every metacharacter in dynamic patterns, so user input can only ever match literally instead of acting as syntax.
Request fullscreen on one element with requestFullscreen, track it with document.fullscreenElement, and listen to fullscreenchange for Esc exits.
setCustomValidity attaches a custom message that fails validity until cleared with an empty string, covering rules the built-in constraints cannot express.
setProperty writes CSS custom properties with optional important priority, and getComputedStyle reads back the parsed value for state-driven theming.
Move a text field caret or preselect a span with setSelectionRange after programmatic writes, and read selectionStart, selectionEnd, selectionDirection back.
Object spread skips null and undefined sources while array spread throws TypeError, so config merging needs no guard but list concat does.
Wrap a DOM update in document.startViewTransition so the browser cross-fades old and new snapshots, honoring prefers-reduced-motion with a direct update.
Await stream completion with finished(): the promise settles when the stream drains and rejects when it is destroyed with an error.
Node stores timer delays in 32 bits: delays above 2147483647 ms clamp to 1 ms with an overflow warning, so long schedules must re-arm chained timers.
Drive periodic work with timers/promises setInterval as an async iterable and cancel it mid-loop by aborting the signal passed in options.
TreeWalker walks a subtree through a NodeFilter callback, so text extraction can drop regions like b-draft text without hand-written recursion.
TypedArray.sort compares elements numerically while Array.sort falls back to string comparison, so the same digits sort differently in each.
Compose command-line lines with %s %d %j placeholders; extra arguments are appended instead of dropped and objects pass through inspect formatting.
Define an [inspect.custom] method and console.log prints your business shape instead of the default object dump — fields stay untouched.
Parse media type strings with the MIMEType class: type, subtype, essence, and a MIMEParams map you can read, iterate, mutate, and re-serialize.
Parse .env-style text with the built-in parseEnv: comments are skipped, quotes are stripped, and empty values come back as empty strings.
Separate platform Promises from thenables, Dates from ISO strings, and async functions from promise-returning functions with node:util types.
visualViewport tracks the visually visible region, so a fixed banner can approximate keyboard height from innerHeight minus the viewport height.
Request a screen wake lock sentinel and re-acquire it on visibilitychange, because the browser releases the lock whenever the tab hides.
Feed a watchdog timer after every progress step; when work stalls past its budget the timer aborts the task through AbortController with a stall reason.
Persist WebCrypto keys as JWK: generateKey an extractable AES-GCM key, exportKey its JWK, then importKey it back and verify the material matches.
Detect popup blocking by checking window.open for null, then fall back to same-tab navigation and watch win.closed for the popup lifecycle.
XMLSerializer turns a DOM document or element back into markup: document form includes the doctype, element form does not; edits serialize as they stand.
Element.append takes any mix of nodes and strings with no return value, while appendChild takes a single node and hands it back for chaining.
concat returns a fresh array merging arguments and spreads values shallowly: nested arrays stay nested and objects are shared by reference with the source.
lastIndexOf returns the position of the last match, honoring a fromIndex that starts the backward scan; out-of-range negatives skip the search and return -1.
Listeners outside a shadow root only see the host as event.target; composedPath() returns the real inner chain, truncated to the host for closed roots.
setDate and setMonth carry overflow into the following month — January 31 plus one month lands on March 3 — while day 0 steps back to the previous month-end.
delete unlinks an own property so in and hasOwn both miss it, assigning undefined keeps the key, and delete on an array leaves a hole without shrinking length.
Events built with new Event and dispatched from script always carry isTrusted false, so listener entry points can reject synthetic submissions early.
In bubbling event.target stays at the element actually hit while event.currentTarget names the element running the listener, enabling one delegated handler.
Emitting error without an error listener throws immediately instead of being dropped, so every EventEmitter should register its error handler first.
The ** operator matches Math.pow, groups right-to-left so 2 ** 3 ** 2 is 512, accepts fractional exponents, and overflows past double range into Infinity.
innerHTML turns indentation into text nodes, so firstChild can hand back whitespace while firstElementChild and nextElementSibling stay on real elements.
globalThis exists in browsers, workers and Node while window and global do not, so library code reads and registers runtime flags through one universal handle.
in tests key existence across the prototype chain: sparse array holes fail, keys holding undefined pass, and Object.hasOwn limits the check to own properties.
stringify refuses cyclic object graphs with a TypeError, so log paths must break the cycle first or steer around the cyclic key with a replacer.
Duplicate JSON keys are legal syntax; JSON.parse keeps the last assignment and the reviver only sees merged properties, so overwritten values are unrecoverable.
Node.contains answers whether one node sits inside another, inclusive of itself, which is the check a click-outside handler needs before closing a menu.
Inverting a record with Object.entries and fromEntries gives reverse lookups, but duplicate values collide silently unless the inverse collects lists.
Object.is treats NaN as identical to itself and keeps -0 distinct from 0, the two places where the === comparison disagrees with intended identity.
The storage event reaches every same-origin page except the one that wrote, carrying key, oldValue, and newValue; a null key means another tab called clear.
String() converts any value to text, including null, undefined and symbols; .toString() is a method call and throws TypeError on nullish receivers.
A recursive pass over Object.entries and Object.fromEntries drops null, undefined and empty-string fields before persistence while keeping 0 and false intact.
refresh() rearms a running timer in place, the primitive behind idle watchdogs: every heartbeat pushes the deadline out without recreating the timeout.
Each transitioned property fires its own transitionend carrying propertyName and elapsedTime, while an interrupted transition fires transitioncancel instead.
Object coercion consults valueOf before toString: arithmetic gets the number, string contexts get the text, objects with neither become [object Object].
flat() unwraps one level by default, a depth argument digs deeper, sparse holes disappear, and flatMap is just map followed by flat(1).
push and unshift return the new length while pop, shift, and splice return removed elements — array mutator return values differ by design.
The beforeinput event carries an inputType for the pending edit, so a contenteditable can preventDefault formatting commands before they land.
BigInt.asUintN and asIntN reinterpret values at a fixed bit width, giving counters and checksum fields the modular wrap hardware registers have.
Buffer write and read methods take a byte offset argument, so wire-format headers place each field at a fixed home and round-trip exactly.
Multiplying the canvas backing store by window.devicePixelRatio and scaling the context keeps lines crisp on high-DPI displays.
compositionend carries the IME-committed string, so validators can skip compositionupdate drafts and check only final input values.
console.time/timeEnd bracket a span under one label, timeLog prints mid-span checkpoints, and count tracks how often a label fired with deterministic output.
Default parameter expressions re-evaluate at call time and can read earlier parameters, so counters and dependent defaults behave predictably.
DOMContentLoaded marks a parsed DOM while load waits for every subresource; late scripts guard on readyState instead of assuming the phase.
Error.isError tests the internal slot, so fake message objects fail, cloned errors pass, and unknown catch values get one honest classification.
events.on exposes an EventEmitter as an async iterable; when the passed AbortSignal fires the loop raises AbortError, so consumers can bound how much they read.
readAsDataURL turns a picked image file into a data: URL string, giving an img preview without any object URL that must be revoked.
forEach calls async callbacks without awaiting them, so the loop ends before the work does; for...of awaits sequentially and Promise.all waits in parallel.
fs.watch streams change and rename events for a directory; debounce writes deliberately and always close the watcher so the process can exit.
A finally block inside a generator executes when return() or throw() terminates it — the cleanup hook fires on every shutdown path, not just next().
getComputedStyle returns the effective value after cascade and unit resolution, so 2em reads back as pixels, and only the inline style stays writable.
Headers.append joins repeated values with a comma while set replaces them, and getSetCookie returns Set-Cookie entries individually because joining corrupts.