AI 资讯
Offline Sync in the Browser Without a Framework
I've been building apps with IndexedDB for years. The local part works fine — store data, query it, show it on screen. The hard part is keeping that data in sync with a server when the network comes and goes. Most tutorials show you how to build an offline app with a framework. Firebase, RxDB, WatermelonDB. Those work, but they bring their own abstractions, their own sync protocols, their own opinions. I wanted something simpler. A database with a sync API that doesn't dictate how my backend works. Here's the setup I landed on. npm: npm install ctrodb Docs: ctrodb.vercel.app/docs/sync/overview What We're Building A notes app that works offline. Create and edit notes on the train, in a tunnel, on a plane. When the network comes back, everything syncs automatically. The database is ctrodb (zero-dependency, browser-based). The backend is anything that speaks HTTP. Step 1: Database Setup import { Database , syncPlugin , HttpTransport } from " ctrodb " const db = new Database ({ name : " notes-app " , schema : { version : 1 , collections : { notes : { fields : { title : { type : " string " , required : true }, body : { type : " string " }, updatedAt : { type : " string " , default : () => new Date (). toISOString () }, }, indexes : [{ field : " updatedAt " }], }, }, }, }) await db . connect () Every collection you want to sync needs a timestamp field. The sync engine uses it to order changes and detect conflicts. Plugins are passed in the Database constructor via plugins array: const transport = new HttpTransport ({ url : " https://api.myapp.com/sync " , }) const db = new Database ({ name : " notes-app " , schema : { ... }, plugins : [ syncPlugin ({ transport })], }) await db . connect () The transport takes a single base URL and appends /push and /pull automatically. The sync plugin hooks into every write operation and records it in the change log. The plugin exposes devtools that take the database instance as their first argument: import { inspectSyncQueue , retryFaile
开源项目
🔥 kunchenguid / lavish-axi - HTML is the new markdown. Lavish is the new editor for your
GitHub热门项目 | HTML is the new markdown. Lavish is the new editor for your HTML artifacts. | Stars: 1,811 | 265 stars this week | 语言: JavaScript
AI 资讯
Model Kombat: The LLM Fighting Game!
Ever wondered what would happen if the world's leading Large Language Models settled their benchmark disputes in a 2D cybercity arena? It's easy to look at model performance on standardized benchmarks (like MMLU, MATH, or HumanEval). It is much more fun to visualize their underlying architectures, parameter scales, and hardware constraints as a retro-cyber fighting game. So, we built Model Kombat (Mixture of Experts Edition)! 🕹️ Play Directly Here 🎮 Launch Game in Full Screen 🧬 Playable ML Concepts Explained This isn't just a basic stick-figure fighting game. Every mechanic—from rendering complexity to the speed at which characters recover—is a direct, playable representation of real-world Large Language Model engineering. 1. 📐 Parameter Scaling vs. Render Tiers A model's representation capacity (intelligence) scales with its parameter count. In Model Kombat, a fighter's visual complexity, joint detail, and rendering fidelity directly reflect its real-world parameter size: Tier 1 (< 5B Parameters - Gemma 2B, Llama 3.2 3B) - Primitive Capsules : Drawn as simple, single-color flat limbs with low joint segmentation. This visualizes the limited representation capacity and coarse output resolution of small edge models. Tier 2 (7B - 14B Parameters - Mistral 7B, Claude Haiku) - Simple Vectors : Structured as thin skeletal wireframe vectors. Tier 3 (14B - 35B Parameters - Gemini Flash, Mixtral) - Two-Tone Vectors : Rendered as dual-color, layered vector limbs. Tier 4 (35B - 100B Parameters - Llama 8B, Claude Sonnet) - Cyborg Shading : Rendered as detailed vector cylinders with dynamic code particle streams flowing along their limbs. Tier 5 (> 100B Parameters - o3, GPT-4o, Claude Opus) - Quantum Vectors : Rendered as glowing vector limbs with digital matrix code particles, soft drop-shadow depth buffers, and real-time afterimage motion trails. 2. ⚡ Reasoning Tokens & KV-Cache Overcharging Instead of arbitrary "mana" or "stamina," fighters charge a Ki bar representing interna
AI 资讯
I Built a Browser From Scratch, and It Finally Renders the World's First Website Like Chrome Does
A while back I set myself a slightly unhinged goal: build a web browser from scratch in Node.js and Electron no external HTML/CSS/layout libraries, everything hand-rolled. URL parser, TCP/TLS socket, HTTP pipeline, HTML tokenizer, DOM builder, CSS tokenizer, CSS parser, style matcher, layout engine, canvas renderer. All of it, from zero. so,I called it Courage Browser . This week, after dozens of daily sessions, I hit a milestone that felt disproportionately satisfying: Courage now renders info.cern.ch the very first website ever put on the internet almost pixel-for-pixel identical to real Chrome. It sounds small. It is not small. Getting there meant chasing down bugs across nearly every layer of the browser. Why info.cern.ch If you haven't seen it, info.cern.ch is CERN's preserved copy of Tim Berners-Lee's original website. It's about as simple as HTML gets — one heading, a paragraph, a bulleted list of links. No CSS file, no JavaScript, no styling of any kind beyond what a browser applies by default. Which is exactly why it's a great test case. If your browser can't get a page with zero author CSS to look right, it has no business trying to render anything more complex. Default styling headings being bold, links being blue and underlined, bullets showing up in the right place has to work before anything else does. The bugs I found by just... comparing screenshots I put a screenshot of Courage's render side-by-side with Chrome's and started listing differences. Two jumped out immediately: The <h1> wasn't bold in Courage, even though it clearly should be. The links had underlines but weren't blue , they were rendering in the default text color. Neither of these had anything to do with what I was originally working on that day (CSS attribute selectors, for an upcoming GitHub-rendering push). But they were visible, they were wrong, and they were small enough to fix in one sitting. So I did. Bug #1: styles computed before they were applied Courage has a defaultRules ar
开发者
The Key That Unlocks Everything: Prototype Pollution in JavaScript
Imagine a hotel where every room key is cut from a master template. When a guest checks in, the front desk hands them a key that opens only their room. Simple enough. Now imagine a guest who, during check-in, sneaks a tiny modification into the key-cutting machine itself — changing the template so that every new key cut from that moment on also opens the manager's office, the safe, and the server room. The guest didn't break a lock. They didn't clone anyone's key. They changed the factory that makes all keys. That factory is JavaScript's Object.prototype . And the attack is called Prototype Pollution .
AI 资讯
The JDK's forgotten JMX protocol
Every Java engineer who has connected JConsole — or JDK Mission Control — to a server in another network segment knows the ritual. Open the JMX port. Discover that RMI quietly opened a second port — random by default. Pin it with a system property nobody remembers without searching. File a firewall ticket for both. Wait. What fewer people know: the JMX specification shipped with the second remote transport that has none of these problems. One socket, one port, TLS underneath if you want it. It's called JMXMP — the JMX Messaging Protocol. It lost for the least mysterious reason in software — RMI shipped by default, JMXMP was a separate download, and defaults win — and its reference implementation has been effectively abandoned since around 2008. Yet, it never quite died. Code that refuses to die usually knows something. I didn't set out to resurrect it. I fell into it. The port dance, briefly The default remote JMX stack rides on RMI. The connection URL tells you most of the story: service:jmx:rmi:///jndi/rmi://host:1099/jmxrmi I'll spare you the full anatomy behind that URL — there's a JNDI lookup in it, and that second, dynamically assigned port from the ritual above; few people ever learn the details, which is rather the point. Dynamic ports were a reasonable design for 1999's flat networks. Between today's firewalls, NAT, and containers, they're friction — not because RMI is bad, but because the network it was designed for no longer exists. The JMXMP URL: service:jmx:jmxmp://host:9875 One socket. TCP in, TCP out. That's the whole networking story. How I ended up in this codebase I maintain JConsoleBooster , a modernized JConsole. It shipped fine for years on the 2008-era JMXMP jar — the one historically distributed as jmxremote_optional / jmx-optional , out of Sun's OpenDMK project, republished over the years by several parties because people kept needing single-socket JMX. Then I moved the app to a jlink -built runtime. An automatic module from 2008 does not coo
AI 资讯
Conditional Statements in JavaScript
Conditional Statements Conditional statements allow JavaScript to execute different blocks of code based on whether a condition is true or false. if - The if statement executes a block of code only if the condition is true. if...else - Use if...else when you want one block of code to run if the condition is true and another block if it's false. if...else if...else - Use this when you have multiple conditions to check. switch statement - The switch statement is used when you have many possible values for one variable. Nested if statement - You can also write an if statement inside another if. Ternary Operator - An optimized one-line shorthand for standard if...else blocks ** If Statement ** let age = 20 ; if ( age >= 18 ) { console . log ( " Eligible to vote " ); } //Output: Eligible to vote ** if else Statement ** let age = 16 ; if ( age >= 18 ) { console . log ( " Eligible to vote " ); } else { console . log ( " Not eligible to vote " ); } // Output: Not eligible to vote ** if ... else if ... else ** let marks = 85 ; if ( marks >= 90 ) { console . log ( " Grade A " ); } else if ( marks >= 75 ) { console . log ( " Grade B " ); } else if ( marks >= 50 ) { console . log ( " Grade C " ); } else { console . log ( " Fail " ); } // Output: Grade B ** switch statement ** let day = 3 ; switch ( day ) { case 1 : console . log ( " Monday " ); break ; case 2 : console . log ( " Tuesday " ); break ; case 3 : console . log ( " Wednesday " ); break ; default : console . log ( " Invalid Day " ); } // Output: Wednesday // Important: The break statement stops the execution after the matching case.We must compulsory to use break statement because if you don't use break, JavaScript will continue executing the next cases even the output is correct. ** Nested if Statement ** let age = 20 ; let hasLicense = true ; if ( age >= 18 ) { if ( hasLicense ) { console . log ( " You can drive. " ); } } // Output: You can drive. ** Ternary Operator ** let isLoggedIn = true ; let systemMessage = is
AI 资讯
What a Refinery Taught Me About CI Pipelines
I’m currently relearning the Core Three — HTML, CSS, and JavaScript — as I work toward becoming a full-stack JavaScript developer. Before I came back to learning software, I spent 22 years working industrial turnarounds. One lesson from that world has followed me into software engineering: Never trust a single point of failure. In industrial maintenance, there’s a safety practice called double block-and-bleed . Instead of trusting one isolation valve, you use two independent valves with a bleed point between them. If one valve leaks, you know immediately. The entire system assumes individual components can fail. Safety doesn’t come from perfect parts. It comes from independent layers of protection. That idea completely changed how I think about CI pipelines. When I first started relearning web development, my mindset was simple: Run Lighthouse. Everything green? Great. 100 across the board locally? Even better. Ship it. Different results after deployment? Uh-oh. Now I see Lighthouse as one checkpoint — not the finish line. A fast website can still have accessibility issues. An accessible site can still have broken metadata. Good SEO won’t catch rendering bugs. Passing unit tests won’t tell you if the generated HTML is malformed. Every tool has blind spots. No single tool should get the final vote. So instead of asking: “Did my tests pass?” I ask: “What kinds of failures could still slip through?” That question naturally leads to layered validation. Formatting Linting Type checking Accessibility checks Performance audits HTML validation SEO analysis Manual review None of these tools is perfect. Together, they’re much stronger than any one of them alone. The more I learn about software, the more I find myself applying lessons from heavy industry. Different environment. Different risks. The same engineering mindset. Assume components will fail. Design systems that fail safely. That’s becoming the philosophy behind every test matrix and CI pipeline I’m designing. What’s
开发者
A Beginner's Guide to Installing and Using Node.js on Windows
Have you ever wondered how massive modern platforms like Netflix, PayPal, and LinkedIn handle millions of users simultaneously without crashing? The secret weapon behind much of the modern web is Node.js. Traditionally, JavaScript—the language that makes websites interactive—could only run inside a web browser like Chrome or Edge. Node.js changed the game by freeing JavaScript from the browser, allowing it to run directly on your computer. This means you can use it to build backend servers, automate boring computer tasks, or run powerful development tools. If you are intimidated by coding, don't worry. This guide will take you from zero to running your very first Node.js program on Windows, step-by-step. Prerequisites Before we begin, you only need two things: A computer running Windows 10 or 11. An active internet connection to download the installer. No prior coding experience or command-line knowledge is required! Step-by-Step Instructions Download the Node.js Installer First, we need to grab the official installation file. Open your web browser and go to the official website: nodejs.org. You will see two primary options to download. Always choose the LTS (Long Term Support) version. The LTS version is heavily tested, stable, and less likely to give you unexpected errors. Click the Windows Installer button to download the .msi file to your computer. Run the Setup Wizard Once the download finishes, navigate to your Downloads folder and double-click the file to open the setup wizard. Click Next on the welcome screen. Accept the license agreement and click Next. Leave the default installation folder as it is (C:\Program Files\nodejs) and click Next. On the "Custom Setup" screen, leave everything at its default and click Next. Important Step: You will see a checkbox that asks to "Automatically install the necessary tools." Leave this unchecked for now to keep your setup simple and fast. Click Next. Finally, click Install. If Windows asks for permission to make change
AI 资讯
How to Hunt a Bug at 10 PM 🌙
The Story: Picture this: It is 10 PM. I was eating my dinner while adding one final touch to my social media app, Vlox. It should just say "Processing..." while generating a card. Simple, right? See the nightmare. 🔥 The Nightmare Scenario 📉 Suddenly, my "Download Card" button broke. htmlToImage started spitting out completely empty 0b images. The hunt was on. Failed Mission Log 🛰️ Attempt 1: Swap to html2canvas 🔄 Result: Error stating the element was not found in the cloned iframe. Verdict: The parent container was completely lost. Attempt 2: Use CoolAlertJS Toast 🍞 Result: It looked ugly and meant loading two different alert libraries for the same job? Not my game. Verdict: Total waste of bundle size. Attempt 3: Append to body + display: none 🙈 Result: The canvas process failed entirely. Verdict: Canvas snapshot engines completely ignore hidden elements. The "Aha!" Moment 💡 Why did the element vanish? Because the card generator lives entirely inside a Swal popup. When you click the download/confirm button, Swal instantly destroys that entire popup DOM tree. You cannot snapshot an element that no longer exists. 👻 The Ultimate Fix 🚀 Inside the new "Processing" popup, I appended the #card-generator-image-preview directly into the new alert container. The element stays alive in the active DOM. The snapshot succeeds perfectly. Clean code. Happy developer. Delicious dinner. Want to see the exact JavaScript code block that fixed it? Drop a comment below or check Vlox on Github .
开发者
Levelo-Js v2: The TypeScript Rebirth
If you have ever built a custom JavaScript framework from scratch, you know that the line between a smooth, memory-clean engine and a total memory-leak disaster is incredibly thin. With version 1, Levelo-Js proved that lightweight reactive UIs could be fast and intuitive. But as codebases grow, raw JavaScript starts to feel like writing code blindfolded. The dreaded undefined is not a function is always lurking around the corner. Today, we are taking a massive leap forward. Meet Levelo-Js v2 —a complete ground-up architectural rewrite, fully re-born in TypeScript, with enterprise-grade build tooling and absolute bulletproof memory management. Let’s dive into what makes v2 an absolute game-changer. The Pillars of the TypeScript Rebirth 1. Full TypeScript Migration & Modern Bundling We didn't just add types; we transformed the entire runtime engine core and internal modules from .js to .ts . Every piece of code is now strictly type-safe, offering self-documenting APIs and flawless IDE autocompletion (IntelliSense) right out of the box. We also waved goodbye to publishing raw, uncompiled source files. Levelo-Js v2 now ships with production bundles powered by tsup . The engine is now pre-bundled into highly optimized, tree-shakable ES Modules ( compiler/index.js ), making your production build lighter than ever. 2. Hierarchical Tracking Context ( owner.ts ) Handling nested reactive scopes and side-effects can easily lead to chaotic state bugs if not tracked properly. v2 introduces a robust Reactive Ownership Architecture . This creates a clean parent-child tracking hierarchy, ensuring that nested state updates always know exactly where they belong in the application tree. 3. Ownership-Driven Effects & Zero Memory Leaks Memory leaks are the silent killers of Single Page Applications (SPAs). In v2, our core effect() engine has been deeply integrated with the new ownership layer. The breakthrough? It now auto-disposes stale tracking dependencies automatically. We ran heap
AI 资讯
I Got Tired of Hunting for Free Online Tools. So I Built 1000+ of Them — All Client-Side, Zero Backend.
I Got Tired of Hunting for Free Online Tools. So I Built 1000+ of Them — All Client-Side, Zero Backend. Every time I needed a simple tool — format JSON, resize an image, generate a QR code — I'd open Google, search for a "free online tool," and land on some sketchy site with 47 pop-up ads, a 10MB file size limit, and a $9.99/month "premium" upgrade staring me in the face. Sound familiar? I knew there had to be a better way. So I built one. And then another. And... well, 1000+ tools later (1052 to be exact, across 2130+ bilingual pages), here we are. What started as a weekend project turned into an obsession: a completely free, ad-light, privacy-first toolbox that does everything in your browser. No uploads. No servers. No accounts. No BS. 🚀 The Self-Imposed Constraints The most interesting part? I gave myself some pretty extreme constraints: Constraint Why 100% static HTML/JS No server, no database, no build step $0 hosting GitHub Pages — literally free forever Works offline Everything runs client-side, so once loaded, it just works Bilingual Every tool has an English + Chinese version No frameworks Vanilla HTML, CSS, and JavaScript — no React, no Vue, no build tools SEO-first Every page has Schema.org structured data, OG tags, and sitemap integration Why these constraints? Because I wanted to prove that you can build something genuinely useful without any recurring costs, complex infrastructure, or venture capital. Just pure engineering. 🔧 The Architecture (If You Can Call It That) The whole thing is beautifully simple: webtools-cn.github.io/tools-site/ ├── index.html ← Homepage with category filtering ├── en/index.html ← English homepage ├── sitemap.xml ← Auto-generated, ~2130 URLs ├── llms.txt ← AI search optimization ├── [tool-name]/ ← Each tool is a standalone folder │ └── index.html ← Self-contained HTML + JS + CSS └── en/[tool-name]/ ← English version of each tool └── index.html Each tool is a completely standalone HTML file . No build process, no framework,
AI 资讯
How I Kept a Live Chat Feed Smooth at 3,700+ Messages
I built LiveShop , a mini live-shopping stream UI, to answer a question I kept running into as a frontend-curious grad: tutorials teach you how to render a list, but they never teach you what happens when that list gets hit with the kind of traffic a real live stream produces. So I built something that would force the problem to show up, then fixed it, then measured whether the fix actually worked. The setup LiveShop simulates a live-shopping broadcast - the kind of interface a small merchant might use to sell products while streaming. A mock event engine fires chat messages, reactions, and purchase notifications on an interval, standing in for what a real WebSocket connection to a streaming backend would deliver. On top of that sits a chat feed, a scrollable product carousel, and a floating reaction animation layer. None of that is unusual. The interesting part started once I asked: what happens when message volume spikes? Where it breaks A naive chat feed is just messages.map(m => <ChatRow key={m.id} {...m} />) . It's the first thing anyone reaches for, and it's fine — right up until it isn't. At 50 messages, nothing looks wrong. At a few hundred, every new message triggers a full re-render pass across every row in the DOM, including the hundreds that have already scrolled out of view and that nobody can see. The browser is doing layout and paint work for pixels that aren't on screen. In a real live stream, this is exactly the wrong failure mode, because message volume doesn't arrive evenly. It spikes — right after a product drop, right when something funny happens on stream, right when a popular creator says something quotable. That's precisely the moment a chat feed can't afford to stutter, and precisely the moment a naive implementation is most likely to. What I measured Rather than guess whether this mattered, I built a way to test it directly. LiveShop has a "Simulate spike" button that fires 500 messages instantly, plus a live FPS readout using requestAnimat
AI 资讯
Your Loom App Quietly Became a Thread Pool Again: A Field Guide to Virtual Thread Pinning
The incident that taught me to respect pinning looked like nothing. A service freshly migrated to virtual threads, a load test that plateaued at about 420 requests per second no matter how much traffic we threw at it, CPU sitting at 9%, zero errors, zero warnings, nothing in the logs. The machine had 8 cores, and the one downstream HTTP call in the hot path took about 19 ms. Do the arithmetic: 8 × (1000 / 19) ≈ 421. The service that was supposed to scale to millions of virtual threads was serving exactly one request per CPU core. Loom had quietly handed us back a bounded thread pool, and the code looked perfectly innocent. That failure mode has a name — pinning — and this is the field guide I wish I'd had that night: what it is, the two (and only two) things that cause it, what JDK 24 changed, and how to catch it before your throughput graph does. What pinning actually is A virtual thread doesn't own an OS thread. It runs on a small pool of platform threads called carrier threads — concretely, the workers of a dedicated ForkJoinPool living in a thread group named CarrierThreads , with default parallelism equal to Runtime.availableProcessors() . When a virtual thread blocks — on I/O, a lock, a queue — it normally unmounts : it saves its stack, steps off the carrier, and frees that carrier to run another virtual thread. That unmount is the entire trick that lets a handful of OS threads serve millions of virtual ones. Pinning is when the unmount can't happen. The virtual thread blocks but stays mounted, and its carrier sits there doing nothing useful for the whole duration. One pinned carrier is a rounding error. But the default carrier pool is only as big as your core count, so if a hot path pins routinely, you pin every carrier at once — and then no virtual thread anywhere makes progress. That's not a slowdown; it's scheduler starvation, and from the outside it looks a lot like a deadlock. You can raise the ceiling with -Djdk.virtualThreadScheduler.parallelism=N , bu
开发者
Checkout my new post about Typescript.
The Complete TypeScript Mastery Guide Navneet Verma Navneet Verma Navneet Verma Follow Jul 10 The Complete TypeScript Mastery Guide # typescript # webdev # systemdesign # tutorial 5 reactions Add Comment 54 min read
AI 资讯
Day 128 of Learning MERN Stack
Hello Dev Community! 👋 It is officially Day 128 of my software engineering marathon! Today, I tackled an essential lifecycle design challenge in modern frontend development: managing persistent browser loops, orchestrating ticking background workers, and mastering Timer Cleanups inside the useEffect Hook ! ⚛️⏱️💻 I put these architectural paradigms into action by engineering a lightweight, responsive Real-Time Clock Application that tracks exact server-client time down to the second without triggering rogue background processor spikes! 🛠️ Deconstructing the Day 128 Asynchronous Scheduler As captured across my clean system workspace configurations in "Screenshot (286).png" and "Screenshot (287).png" , the scheduling mechanism enforces strict resource allocation: 1. Initializing Reactive Temporal State Managed our standard state anchor using native JavaScript runtime Date models to trigger instant re-renders upon completion of each interval cycle: javascript const [time, setTime] = useState(new Date());useEffect(() => { let intervalId = setInterval(() => { setTime(new Date()); }, 1000);
AI 资讯
Day 125 of Learning MERN Stack
Hello Dev Community! 👋 It is officially Day 125 of my software engineering marathon! Today, I crossed an elite milestone in frontend data architecture: moving completely away from local hardcoded mock lists by connecting my centralized state management infrastructure to live third-party servers using the Fetch API alongside Async/Await ! ⚛️🌐⚡ Now, the social media feed dynamically handles server-side data models, passes payloads to an active state reducer, and broadcasts states down to presentation layers via a custom Context portal! 🛠️ Deconstructing the Day 125 Async Network Lifecycle As shown inside my development setup across "Screenshot (279).png" , "Screenshot (280).png" , and "Screenshot (281).png" , the application state engine is clean and modular: 1. Extensible Central State Reducers ( PostList.jsx ) Engineered explicit structural actions inside the reducer core to seamlessly support both user generation and full-scale network array overriding: javascript } else if (action.type === "NEW_INITIAL_POSTS") { NewPostValue = action.payload.posts; }
AI 资讯
Node.js Internals Explained by Uncle to Nephew — Part 4: Express Plumbing, Error Handling & The Full Roadmap
Bonus round. Parts 1–3 covered why Node exists, what's happening inside it, and the full request journey. This part mops up the pieces that didn't fit anywhere else — the Express plumbing, error handling, and a checklist to test yourself against. Saturday, Round 4 Nephew: Uncle, one more round? I promise this is the last one for a while. Uncle: pours chai — you said that last time too. Fine, what's bugging you now? Nephew: Small things, actually. express.json() , cookie-parser , express.Router() — I use all of them, copy-pasted from old projects, but I couldn't explain any of them if you asked me directly. Uncle: That's exactly the right instinct — the things you copy-paste without understanding are always the things that break at 2 AM. Let's fix that. Part 4.1 — Two Directions Node Never Confuses Uncle: Before plumbing, one small but important idea that ties Parts 2 and 3 together. Everything Node does falls into exactly two directions . DIRECTION 1 — Incoming Events "The outside world is telling Node something happened" OS → libuv → Event Loop → Your JavaScript Examples: HTTP request arrives, TCP connection opens, WebSocket message arrives DIRECTION 2 — Outgoing Async Operations "Your JavaScript is asking Node to go do something" JavaScript → libuv → Worker Thread → OS → Disk/DB ↓ result comes back through libuv → Event Loop → your callback Examples: fs.readFile(), crypto.pbkdf2(), dns.lookup() Nephew: So an incoming HTTP request and a fs.readFile() call both eventually pass through libuv and the event loop — but they enter from completely opposite directions? Uncle: Exactly. One is the world pushing something at Node. The other is Node reaching out to go get something. Same event loop handles both, but the journey to get there is different — an HTTP request never touches the thread pool; a file read almost always does. Incoming HTTP Request: File Reading: Browser JavaScript | | OS libuv | | libuv Worker Thread | | Event Loop Operating System | | JavaScript Disk |
AI 资讯
Make AI Agents See Your Website
AI coding agents are now part of the developer workflow. Whether we like that shift or hate it, users...
AI 资讯
RxJS in Angular — Chapter 9 | Timing Operators — debounceTime, throttleTime, interval & More
👋 Welcome to Chapter 9! Imagine a user typing in a search box. They type "i", "ip", "iph", "ipho", "iphon", "iphone" — 6 keystrokes in 2 seconds. Do you really want to make 6 API calls ? Of course not! You want to wait until they stop typing and then search once. That's what timing operators solve. They control when and how often values flow through your stream. ⏱️ debounceTime() — Wait for the Silence debounceTime(ms) waits until there's a pause of ms milliseconds, THEN lets the latest value through. Think of it like this: "Ignore everything until they stop for a moment." Like a person who waits for you to finish talking before responding. import { debounceTime } from ' rxjs/operators ' ; // User types fast: 'i' → 'ip' → 'iph' → 'ipho' → 'iphon' → 'iphone' // debounceTime(400) waits 400ms of silence, then sends 'iphone' only searchControl . valueChanges . pipe ( debounceTime ( 400 )) . subscribe ( term => { this . searchProducts ( term ); // Only called ONCE with 'iphone'! }); Timeline: Type 'i' → [400ms timer starts] Type 'ip' → [reset timer] Type 'iph' → [reset timer] Type 'iphone'→ [reset timer] ... 400ms silence ... EMIT: 'iphone' ✅ Real Angular Example — Smart Search Box import { Component , OnInit , OnDestroy } from ' @angular/core ' ; import { FormControl } from ' @angular/forms ' ; import { Observable , Subject } from ' rxjs ' ; import { debounceTime , distinctUntilChanged , switchMap , startWith , takeUntil } from ' rxjs/operators ' ; @ Component ({ selector : ' app-search-box ' , template : ` <div class="search-wrapper"> <input [formControl]="searchControl" placeholder="Search products..." (keyup.escape)="clearSearch()"> <span *ngIf="isLoading" class="spinner">🔄</span> <button *ngIf="searchControl.value" (click)="clearSearch()">✕</button> </div> <div class="results-count" *ngIf="(results$ | async) as results"> Found {{ results.length }} results </div> <div class="results"> <div *ngFor="let item of results$ | async" class="result-item"> <strong>{{ item.nam