Abortable fs/promises Reads With AbortSignal
Pass an AbortSignal into fs/promises options so a caller that already timed out rejects the read immediately without touching the file.
Page 8 of 50
Pass an AbortSignal into fs/promises options so a caller that already timed out rejects the read immediately without touching the file.
List whole directory trees with readdir({ recursive: true, withFileTypes: true }) and get Dirent objects that carry parentPath for each entry.
Read volume-level numbers with fs.statfs: block size, total and free space, unprivileged availability, inode slots, and a used-percent calculation.
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].
base64.b32encode emits only A-Z and 2-7 so backup codes survive handwriting and reading aloud; decoding restores the stripped padding with a modulo trick.
Two dicts kept in sync give both directions of a lookup; adds and removes must touch both sides and duplicates must be rejected at the entry point.
Recursive inorder, preorder, and postorder walks visit a binary tree in three different orders, and a deque drives the level-order variant.
True, 1, and 1.0 compare equal and hash equal, so they occupy one dict slot; normalize keys to strings when the source type has to stay distinguishable.
Iterating bytes yields integers while iterating str yields one-character strings, so comparing bytes against str silently fails until you decode.
Bottom-up DP computes the fewest coins per amount and a choice table backtracks the exact denominations, returning -1 when the amount is unreachable.
os.path.commonpath computes the longest common parent for grouping and prefix stripping; comparing it against a base directory detects escaped paths.
field(metadata=) hangs display hints on dataclass fields, and fields() returns them as read-only mappings that drive formatting and serialization.
deque.rotate(-1) slides the chosen head item to the tail in one in-place step, turning a fixed list of endpoints into a fair round-robin selector.
dict.fromkeys binds every key to the same mutable object, so appending through one key mutates all rows; a comprehension builds an independent container.
Subclass dict and implement __missing__ to give subscript lookups a custom fallback or a clearer KeyError; .get and membership checks bypass the hook.
Adding or deleting keys while iterating a dict raises RuntimeError after the mutation lands, so structural changes need a key snapshot or a value-only pass.
dict.pop removes a key and returns its value, honoring a fallback for missing keys, while popitem pops the most recently inserted pair and raises on empty maps.
len on str counts code points while len of the UTF-8 encoding counts bytes, so the same text reports different sizes at the language and transport layers.
expandtabs walks each tab to the next tab stop so tab-separated rows line up in a terminal; a tab size wider than the longest cell keeps columns aligned.