AI 资讯
How to Repair Corrupted PDFs in the Browser with Vue 3 and pdf-lib
A corrupted PDF is one of the most frustrating file problems. You have important content inside, but the document won't open, opens with garbled text, or shows missing pages. The file might be damaged from a bad download, a converter error, or a storage glitch. Recovering content from a broken PDF doesn't require complex forensic tools. Often, the individual pages are still readable — it's the document's structure (cross-reference tables, object streams) that's damaged. By extracting pages one by one into a fresh PDF, we can bypass the structural corruption. Here's how to build a browser-based PDF repair tool with Vue 3 and pdf-lib . The repair strategy The core insight: PDF structure and page content are somewhat independent . A PDF can have a broken cross-reference table or missing trailer objects, but the actual page content streams may still be perfectly readable. The repair approach: Load the damaged PDF and attempt to read each page For each successfully read page, copy it to a new PDF document Discard unreadable pages (they're lost anyway) Save the new document This is fundamentally different from "fixing" the original PDF. We're extracting what we can and rebuilding from the ground up. The stack Vue 3 with Composition API pdf-lib for PDF reading and page extraction Vite for bundling The core implementation < script setup lang= "ts" > import { ref } from ' vue ' import { PDFDocument } from ' pdf-lib ' const file = ref < File | null > ( null ) const totalPages = ref ( 0 ) const recoveredPages = ref ( 0 ) const repairing = ref ( false ) const result = ref < Uint8Array | null > ( null ) const error = ref < string | null > ( null ) async function repairPdf () { if ( ! file . value ) return repairing . value = true error . value = null try { const arrayBuffer = await file . value . arrayBuffer () const damaged = await PDFDocument . load ( arrayBuffer , { ignoreEncryption : true , updateMetadata : false , }) totalPages . value = damaged . getPageCount () const resu
AI 资讯
TypeScript Enums Are Still Controversial in 2026: Here Is When to Use Them and When to Reach for `const` Objects
TypeScript Enums Are Still Controversial in 2026: Here Is When to Use Them and When to Reach for const Objects This article was written with the assistance of AI, under human supervision and review. Most TypeScript enum debates stem from a single misunderstanding: developers treat enums as a pure type-level construct when they generate real runtime code. This disconnect creates bundle bloat, unexpected behavior at runtime, and type safety gaps that only surface in production. Teams that reach for enums by default pay a hidden cost in every build. The enum controversy persists because TypeScript enums violate a core expectation: types should disappear at compile time. Unlike interfaces or type aliases that vanish during transpilation, enums produce JavaScript objects that ship to the browser. This runtime footprint matters when bundle size directly affects load time and business metrics. The alternative pattern— const objects with as const assertions—delivers the same developer experience without the runtime overhead. When developers understand the tradeoffs, the choice becomes mechanical: use enums where their runtime behavior adds value, use const objects everywhere else. Key Takeaways TypeScript enums generate runtime JavaScript objects that increase bundle size, while const objects with as const provide the same type safety with zero runtime overhead. Numeric enums enable reverse mapping and bitwise flags, making them valuable for low-level APIs and performance-critical code where runtime lookup is required. The const enum feature eliminates runtime code but breaks module boundaries and fails with external libraries, creating maintenance hazards in shared codebases. Const objects work seamlessly with tree-shaking, module systems, and JSON serialization, making them the default choice for API contracts and configuration. Migration from enums to const objects requires runtime validation at module boundaries to preserve type safety guarantees when data enters your s
AI 资讯
« J'ai fini le tuto Node, et là je suis bloqué » — le mur dont personne ne parle
Tu as fini le tuto. Le vrai, le gros, celui de douze heures. Tu as tout suivi, tout tapé, tout fait tourner. À la fin, l'application marchait. Tu t'es senti capable. Tu t'es dit : « ça y est, je sais faire une API ». Et puis tu as ouvert un dossier vide pour faire la tienne. Curseur qui clignote. index.js . Rien. Pas parce que tu as oublié la syntaxe. Tu la connais. Mais là, tout seul, sans quelqu'un qui te dit quoi taper à la ligne suivante, tu ne sais pas par où commencer. Et cette sensation-là, ce vide entre « j'ai fini le tuto » et « je sais faire », personne ne t'avait prévenu qu'elle existait. C'est de ce mur que je veux parler. Parce que ce n'est pas un défaut chez toi. C'est une étape. 1. Le piège n'est pas le tuto, c'est ce qu'il te cache Un tuto, c'est une suite de bonnes décisions déjà prises pour toi. Quel dossier créer. Quel package installer. Où mettre le fichier de config. Quand extraire une fonction. À chaque embranchement, le formateur a choisi le bon chemin, et toi tu l'as suivi. Tu as tapé du code, oui. Mais tu n'as pris aucune décision. Or coder, le vrai coder, c'est presque que ça : décider. Choisir entre deux structures. Trancher un nom de variable. Décider si ce bout de logique mérite sa propre fonction. Un développeur qui bosse, ce n'est pas quelqu'un qui connaît toutes les réponses — c'est quelqu'un qui sait avancer quand il n'y en a pas. Le tuto t'a entraîné à taper. Il ne t'a pas entraîné à décider. Et c'est exactement la compétence qui te manque devant ton dossier vide. Ce n'est pas un trou dans ton savoir. C'est un muscle que tu n'as jamais sollicité, parce qu'on ne te l'a jamais laissé faire. 2. Pourquoi « un tuto de plus » ne réglera rien Ta réaction instinctive face au blocage, c'est de retourner là où tu te sens compétent. Un autre tuto. Un cours de plus. Une nouvelle techno à cocher. Je comprends le réflexe. Le tuto, c'est confortable : il y a une barre de progression, une fin, une petite dose de « j'ai réussi » à chaque étape. Le d
AI 资讯
I Built a Photo-to-Cross-Stitch Pattern Maker That Runs in Your Browser
Photo-to-cross-stitch conversion looks like a resizing problem. It is not. A pixelated preview can look convincing and still be frustrating to stitch. It may contain too many colors, lack readable symbols, provide no reliable dimensions, or become useless when printed. I built StitchFromPhoto to handle the practical part of that workflow. It turns an image into a counted cross-stitch chart in the browser, lets you tune the result before committing to it, and keeps the source photo on your device. The useful output is a pattern, not a pixelated image A cross-stitch preview only answers one question. It shows roughly what the finished piece might look like. A usable pattern must also tell you how many stitches wide and tall the design is, which thread color belongs in each square, whether similar colors remain distinguishable on paper, and how large the result will be on your chosen fabric. That distinction shaped the app. The color preview is useful, but the symbol chart, thread key, stitch totals, fabric dimensions, and printable pages are the real deliverables. What the photo-to-cross-stitch pattern maker does The workflow starts with a sample image, so anyone can explore the controls before uploading a file. It also accepts JPG, PNG, and WebP images up to 20 MB. The main controls are stitch width, DMC color count, and fabric count. You can choose a pattern from 30 to 120 stitches wide, limit the palette to between 6 and 36 DMC colors, and calculate the finished size for 14, 16, 18, or 22 count Aida. You can move between the original photo, a color stitch preview, and a high-contrast symbol view. The thread key lists every retained DMC color code and the number of stitches assigned to it. Creating and previewing a pattern is free. High-resolution PNG and print-ready PDF downloads are unlocked per source image. I wanted that boundary to be visible before checkout rather than hidden behind the final button. How the browser turns pixels into stitches The conversion pi
AI 资讯
React useEvent Hook: Stable Callbacks Without Stale Closures (2026)
Every React developer eventually meets the same fork in the road. You write an event handler that reads state, pass it to a child or an effect, and now you must choose: leave it as a plain inline function and watch every render create a new reference — breaking React.memo , re-running effects, re-subscribing listeners — or wrap it in useCallback and start playing dependency-array whack-a-mole, where one forgotten dependency means the handler sees state from three renders ago. That second failure mode has a name — the stale closure — and it's arguably the most common React bug in production code. The fix has a name too: useEvent , proposed in an official React RFC in 2022 , and available today as useEvent in @reactuses/core . It gives you a function whose identity never changes across renders but whose body always sees the latest state and props . Both halves of the fork, no trade-off. This post covers the API, the three-line implementation trick that makes it work, how it compares to useCallback and to React 19.2's built-in useEffectEvent , real patterns, and the one rule you must respect (don't call it during render). TypeScript-first. The Problem in Thirty Seconds Here's the bug factory. A chat component sends a heartbeat with the current draft text: function Composer ({ roomId }: { roomId : string }) { const [ draft , setDraft ] = useState ( '' ); useEffect (() => { const id = setInterval (() => { sendHeartbeat ( roomId , draft ); // ⚠️ which draft? }, 3000 ); return () => clearInterval ( id ); }, [ roomId ]); // draft intentionally omitted — we don't want to reset the timer return < textarea value = { draft } onChange = { e => setDraft ( e . target . value ) } />; } The interval closes over the draft that existed when the effect ran — the empty string. Every heartbeat sends '' forever. Add draft to the dependency array and the closure is fresh, but now the interval tears down and restarts on every keystroke . useCallback doesn't help: it has the exact same depen
AI 资讯
How to Set Up Rate Limiting in Nuxt
Rate limiting is one of those things that doesn't feel urgent—until someone hammers your login endpoint at 3am and you wake up to a flooded database and a locked-out user base. I added this to my Nuxt base layer after realising I'd shipped several projects with zero protection on auth routes. Not great. This post walks through the exact setup I now use: Redis-backed, an in-memory fallback when Redis is down, named presets for different sensitivity levels, and a 429 page that shows a live countdown instead of just dying on the user. The structure Three pieces, each with one job: createRateLimiter() — a factory that builds the limiter, using Redis with an in-memory fallback applyRateLimit() — what you call inside handlers to enforce a limit server/middleware/rateLimiter.ts — global middleware so every route gets a baseline for free 1. Install npm install rate-limiter-flexible ioredis rate-limiter-flexible does the heavy lifting: sliding windows, Redis integration, and the insurance fallback pattern we'll use. 2. The factory Create server/utils/rateLimiter.ts : import { RateLimiterRedis , RateLimiterMemory , type RateLimiterAbstract , } from ' rate-limiter-flexible ' import { getRedisClient } from ' ./redis ' export interface RateLimiterConfig { keyPrefix : string // Must be unique per limiter, e.g. 'rl:auth' limit : number // Maximum requests within the window windowSeconds : number } export interface RateLimitResult { allowed : boolean limit : number remaining : number resetAt : number // Unix timestamp in seconds when the window resets retryAfter : number // Seconds until retry; 0 if allowed } function buildLimiter ( config : RateLimiterConfig , ): RateLimiterAbstract { const insurance = new RateLimiterMemory ({ keyPrefix : config . keyPrefix , points : config . limit , duration : config . windowSeconds , }) const redis = getRedisClient () if ( ! redis ) { return insurance } return new RateLimiterRedis ({ storeClient : redis , keyPrefix : config . keyPrefix , points
AI 资讯
I blocked XSS attacks and API Key extraction in the browser by monkey-patching `crypto.subtle`. Why isn't everyone doing this?
Here is how I hardened the browser runtime for a Zero-Knowledge, Non-Custodial FinTech trading terminal. 👇 Client-Side Envelope Encryption: I derive a KEK from the user's password using PBKDF2-SHA256 (310,000 iterations). Then, a secure random 32-byte DEK (AES-256-GCM) encrypts the data. The password NEVER touches the server, and the DEK has a strict 15-min TTL in RAM before a wipe. Secure Enclave Anti-Export Guard: CryptoKeys are generated via crypto.subtle with {extractable: false} . To prevent injected malicious scripts from bypassing the sandbox, I implemented an isolated closure that overrides (monkey-patches) the native browser API: crypto.subtle.exportKey = async function(format, key) { if (isProtectedKey(key)) { _AuditChain.append('EXPORT_ATTEMPT', 'CRITICAL'); throw new Error('Export BLOCKED — unauthorized'); } return _origExport(format, key); }; If our database is breached, hackers find ZERO financial data. If the local session is compromised, runtime gating blocks extraction. Plus, client-side validation rejects API keys with withdrawal permissions enabled (zero custodial risk under MiCA, built for GDPR). The entire architecture runs client-side (WebSocket throttled at 100ms + local AI Advisor), keeping server costs near zero. Where does this runtime isolation logic fail? Why do major SaaS platforms still rely on standard local storage? Let's discuss. 💬
AI 资讯
Project Explanation for my Chesso application
Project High-Level Summary Chesso is a full-stack, real-time multiplayer chess platform engineered to provide low-latency online gameplay. It features real-time move synchronization, authoritative backend match clocks, secure authentication using JWT and Google OAuth, and full chess rule validation. I built it using the MERN stack (MongoDB, Express, React, Node.js) combined with Socket.IO for bi-directional WebSocket communication and Chess.js for move validation and FEN (Forsyth–Edwards Notation) state management. One of the main challenges I solved was building a server-authoritative state and clock synchronization mechanism to prevent client tampering and handle mid-game reconnections gracefully. Tech Stack & Architectural Overview Frontend : React, Vite for fast builds, React for declarative UI updates upon WebSocket events. Backend API : Node.js, Express.js Event-driven, non-blocking I/O ideal for handling multiple concurrent WebSocket connections. Socket.IO : Provides bi-directional socket events, auto-reconnection fallback, and socket room abstraction. Database : MongoDB for flexible JSON-like document model ideal for storing FEN strings, match logs, and user metadata. Auth & Security : Google OAuth 2.0, Passport.js, JWT, bcryptusing standard authentication flow providing password hashing (bcrypt) and session security via JWT tokens. Implementation of matchmaking & Queueing System When a player clicks "Play", the client emits StartGame with their playerID. The server verifies turn ownership (game.currentP === playerID). The move is executed in an isolated server-side Chess() instance (gameSockets.js). If empty, the player is queued and notified via waitingForOpponent. If another player is waiting, waitingQ.shift() pairs them instantly, creates a new game record in MongoDB (GameModel.js), assigns piece colors (white/black), and joins both sockets into a dedicated Socket.IO room named after the gameID. Game Recovery & Reconnection Resilience The server exposes
AI 资讯
Typing Vue 3 provide/inject Without Losing Autocomplete
Strict prop types and typed emits get most of the attention in Vue 3 + TypeScript setups, but provide / inject is where type safety quietly falls apart if you use the API the way the docs show it by default. inject() without a type hint returns unknown , which means every consumer of an injected value either casts it blindly or loses autocomplete entirely — and a typo in the injection key becomes a runtime undefined instead of a compile-time error. The Default Setup Is Untyped by Construction The naive version compiles, but gives you nothing: // Provider provide ( ' theme ' , currentTheme ); // Consumer const theme = inject ( ' theme ' ); // type: unknown Nothing here catches a typo in the key string, and nothing tells the consumer what shape theme actually has. Both problems come from using a plain string as the injection key. InjectionKey Fixes Both Problems at Once Vue exports an InjectionKey<T> type specifically for this. Define it once, typed, and both provide and inject become fully type-checked against the same symbol: // keys.ts import type { InjectionKey } from ' vue ' ; export interface Theme { mode : ' light ' | ' dark ' ; accentColor : string ; } export const ThemeKey : InjectionKey < Theme > = Symbol ( ' theme ' ); // Provider import { ThemeKey } from ' ./keys ' ; provide ( ThemeKey , { mode : ' dark ' , accentColor : ' #4f46e5 ' }); // Consumer import { ThemeKey } from ' ./keys ' ; const theme = inject ( ThemeKey ); // type: Theme | undefined The | undefined in that last type isn't a quirk — it's inject being honest that a consumer might render without a matching provider above it in the tree, which is a real runtime possibility TypeScript is right to force you to handle. Handling the undefined Case Without Littering ?. Everywhere The common mistake is providing a default value to silence the undefined type instead of actually checking for it: const theme = inject ( ThemeKey , { mode : ' light ' , accentColor : ' #000 ' }); // default masks missing pro
开源项目
🔥 WorldFlowAI / everything-claude-code - Claude Code toolkit - agents, commands, skills, rules, and h
GitHub热门项目 | Claude Code toolkit - agents, commands, skills, rules, and hooks for productive AI-assisted development | Stars: 982 | 143 stars this week | 语言: JavaScript
AI 资讯
Express 5 on µWebSockets: same middleware, 2x to 7x
I maintain Fulmine , a drop-in replacement for Express 5 that runs on µWebSockets.js instead of node:http . One line changes: const express = require ( " fulmine.js " ); // instead of require("express") Your middleware keeps working: helmet , cors , passport , morgan , multer , express-session and the rest. The numbers are not mine Benchmarks published by a project about itself deserve suspicion, so let me use somebody else's. HttpArena runs every framework on the same 64-core machine, in containers, under the same rules, and publishes the results. Express and Fastify are on that board too. Requests per second, from their published runs: Profile Fulmine Express Fastify Baseline (query parsing) 1,220,308 607,777 711,263 JSON (dataset + serialization) 1,111,187 395,361 522,201 Short-lived connections 1,026,789 278,163 298,779 Pipelined 7,259,814 1,009,543 1,671,338 Mixed API workload, 16 CPUs 126,282 67,724 75,633 Async Postgres 222,701 169,687 179,169 Upload (20 MB body) 2,154 2,104 1,902 That is 2.0x Express on the baseline, 2.8x on JSON, 3.7x on short-lived connections, 7.2x pipelined , and 1.9x on the mixed API profile. Against Fastify, on the same board, it is 1.7x on the baseline and 2.1x on JSON. Now the honest parts, which matter as much as the table. Look at the upload row: 1.02x. A 20 MB body is memory bandwidth and syscalls, not framework code. Everywhere the cost belongs to a library both servers call, the difference disappears: JSON.parse , zlib, OpenSSL. Speed comes from the framework only where the framework is doing the work. My entry runs in the arena's "tuned" mode, Express's and Fastify's run in "standard". On two profiles I left out of the table, static files and compressed JSON, that difference is decisive, because tuned mode allows hand-written compression and negotiation. Those rows would show 23x and 8x, and they would be measuring my entry's tuning, not the framework. I would rather not quote them. Where the speed comes from Not from one trick
开发者
This is a submission for [Frontend Challenge - Comfort Food Edition, Perfect Landing] 😊
What I Built Gnoke Books works like an actual printed magazine on a table — you grab the...
AI 资讯
Nylo: Building a Privacy-Minimized Analytics Layer Across Domains You Control
Most organizations do not operate a single website. A typical customer journey might move through: company.com ↓ docs.company.com ↓ company-academy.com ↓ company-checkout.com These properties may belong to the same organization, but browsers and analytics systems can treat each domain as a separate visitor and session. Cross-domain measurement is possible with major analytics platforms, but it normally ties the implementation to a specific vendor, transfers an existing measurement identifier through the destination URL, or depends on users authenticating. I built Nylo to explore another approach: Preserve pseudonymous continuity across domains an organization controls, without browser fingerprinting, third-party cookies, or requiring the visitor to log in. Nylo is not intended to identify a person. It is intended to answer a narrower question: Did the same pseudonymous browser journey continue from one authorized domain to another? What Nylo is Nylo consists of: A zero-dependency JavaScript client SDK A server-side event ingestion interface A pseudonymous identifier called a WaiTag A short-lived cross-domain token exchange DNS-based verification of participating domains Configurable event collection Storage adapters for different backend systems The core analytics SDK is available under the MIT License. Production commercial use of the cross-domain WTX-1 functionality uses a separate commercial license. Nylo is designed to function as an analytics collection and continuity layer. It can eventually send events to an existing warehouse or analytics platform rather than requiring organizations to replace their reporting stack. How continuity works Consider a visitor moving between two independently registered domains: Visitor opens site-a.com | v Nylo creates a pseudonymous WaiTag | v Visitor follows an authorized link | v A short-lived token is transferred | v site-b.com verifies the token | v Both events reference the same pseudonymous journey Before enabling cross-d
AI 资讯
Vercel vs Netlify vs Cloudflare Pages: Where Your Side Project Should Actually Live
For a side project, the short answer is: Cloudflare Pages if you want the cheapest ceiling and never think about bandwidth, Vercel if you're on Next.js and want the smoothest developer experience, Netlify if you want a mature all-in-one with forms and identity baked in. All three have a free tier that will host a hobby app fine. The differences that actually bite you show up later — when a post gets traffic, when your build gets slow, or when you outgrow static files and start running server code. I've deployed personal projects on all three over the last couple of years. Below is how I'd choose today, with the real trade-offs rather than the marketing version. What are you actually deploying? Before comparing platforms, be honest about your app, because it changes the answer more than any feature chart: Pure static site (docs, a marketing page, a SPA that talks to an external API): all three are excellent and free. The decision barely matters. Static frontend + a few serverless functions (a contact form handler, an auth callback, a small API): now runtime, cold starts, and function limits matter. A full framework app with server rendering (Next.js App Router, SvelteKit, Remix): now framework-specific adapters and edge/runtime compatibility matter a lot. The takeaway: pick based on your heaviest workload, not your current one — migrating hosts after you've wired up auth and functions is the annoying part. How do the free tiers really compare? This is where these platforms differ the most for hobby use. The headline distinction, as of mid-2026: Cloudflare Pages does not meter bandwidth on its free plan , while Vercel and Netlify both count usage (bandwidth, function invocations, build minutes) against free-tier limits and will ask you to upgrade — or throttle — when you cross them. Concern Vercel (Hobby) Netlify (Free) Cloudflare Pages (Free) Bandwidth Metered, capped Metered, capped Unlimited Build minutes Limited Limited Limited (per-month build count) Serverless/e
AI 资讯
A Privacy-First Browser Workflow for AI Photo Editing
AI photo editors look simple from the outside: upload an image, describe a change, and download the result. The hard part is everything around the model call. If you are building or evaluating a browser-based image editor, the workflow needs to protect the original file, reject bad inputs early, make retries safe, and help the user compare the result with the source. This article walks through a small implementation pattern that does that without turning the UI into a complex desktop editor. 1. Validate the image before upload Do not rely on the file extension. Check the MIME type, file size, and whether the browser can actually decode the image. const ACCEPTED_TYPES = new Set ([ " image/jpeg " , " image/png " , " image/webp " , ]); async function validateImage ( file ) { if ( ! ACCEPTED_TYPES . has ( file . type )) { throw new Error ( " Use a JPG, PNG, or WebP image. " ); } const maxBytes = 10 * 1024 * 1024 ; if ( file . size > maxBytes ) { throw new Error ( " The image must be smaller than 10 MB. " ); } const bitmap = await createImageBitmap ( file ); const dimensions = { width : bitmap . width , height : bitmap . height }; bitmap . close (); if ( dimensions . width < 64 || dimensions . height < 64 ) { throw new Error ( " The image is too small for a useful edit. " ); } return dimensions ; } This catches renamed files, broken images, and tiny inputs before they consume bandwidth or model credits. 2. Treat the prompt as a single edit contract Open-ended chat is useful, but it can make image editing unpredictable. A clearer UI asks for one concrete change at a time: remove the person on the right; replace the background with a plain white wall; repair the crease across the top-left corner; extend the image to a 16:9 frame. The request object should preserve that intent without mixing it with UI state: function buildEditRequest ( file , prompt , options = {}) { const normalizedPrompt = prompt . trim (). replace ( / \s +/g , " " ); if ( normalizedPrompt . length < 5 )
AI 资讯
TypeScript Strict Null Checks in 2026: Real-World Patterns for Handling `undefined` Without the Noise
TypeScript Strict Null Checks in 2026: Real-World Patterns for Handling undefined Without the Noise This article was written with the assistance of AI, under human supervision and review. Most TypeScript null safety problems stem from teams treating strictNullChecks as a boolean toggle instead of a design constraint. The compiler flag eliminates an entire class of production bugs, but codebases that flip it on without adjusting their patterns end up drowning in type assertions and optional chaining operators. The result is worse than the original false confidence wrapped in noise. The fundamental issue is that JavaScript conflates absence and failure. A missing property, an API error, and an uninitialized variable all return undefined or null , but they represent completely different failure modes. When teams enable strictNullChecks without encoding these distinctions into their types, the compiler forces them to handle every potential undefined the same way. That leads to defensive checks that obscure intent and catch nothing of value. The correct approach treats null safety as a type design problem. Discriminated unions encode why a value is missing. Branded types prove non-nullability at the boundary. Type guards narrow only when the business logic demands it. The patterns are simple, but they require understanding what the compiler is actually checking and what guarantees your code actually needs. This post covers the essential patterns teams need to write null-safe TypeScript in 2026 without the noise. Apply these in production and the difference will be immediate. Key Takeaways strictNullChecks eliminates runtime null errors only if your types encode why values are missing, not just that they might be missing. Discriminated unions outperform null returns for API responses because they force exhaustive handling of failure cases at compile time. Non-null assertions ( ! ) are acceptable at proven boundaries where external systems guarantee non-null values, but ne
AI 资讯
Debugging Node.js Like a Pro
Start with the Built-in Inspector Before reaching for external tools, remember Node.js has a built-in debugger. Run your script with --inspect and open chrome://inspect in Chrome to get a full DevTools experience: breakpoints, step-through, console, and even memory profiling. node --inspect app.js For a quick breakpoint without touching the browser, use --inspect-brk to pause on the first line. This is great for debugging startup issues. Use debugger Statements and Conditional Breakpoints Sometimes you need a breakpoint only when a condition is true. Instead of littering your code with if blocks, set a conditional breakpoint in DevTools. Right-click the line number, choose "Add conditional breakpoint," and enter an expression like user.id === 42 . For quick inline debugging, debugger; works but remember to remove it before committing. I often use it temporarily when I'm too lazy to open the DevTools UI. Log Like a Pro with util.inspect console.log of an object prints [object Object] which is useless. Use util.inspect with depth and colors to see nested structures clearly. const util = require ( ' util ' ); console . log ( util . inspect ( myObject , { showHidden : false , depth : null , colors : true })); Or in modern Node, you can use console.dir with { depth: null } for the same effect. Async Stack Traces: Don't Lose the Context Async errors are painful because stack traces often end at the event loop. Node 12+ gives you better async stack traces by default, but you can improve them further by using Error.captureStackTrace in your own error classes. class MyError extends Error { constructor ( message ) { super ( message ); Error . captureStackTrace ( this , MyError ); } } This makes the stack trace point to the caller, not the constructor. Handle Unhandled Rejections and Exceptions Silent failures are the worst. Set up global handlers to log errors properly and exit gracefully. process . on ( ' unhandledRejection ' , ( reason , promise ) => { console . error ( ' U
开源项目
🔥 eze-is / web-access - 给 Claude Code 装上完整联网能力的 skill:三层通道调度 + 浏览器 CDP + 并行分治
GitHub热门项目 | 给 Claude Code 装上完整联网能力的 skill:三层通道调度 + 浏览器 CDP + 并行分治 | Stars: 8,544 | 16 stars today | 语言: JavaScript
AI 资讯
Programmatic SEO with hreflang: One Joke, 17 Languages, Server-Rendered
People type 2+2 into Google. They type 9+10 . They type 7*8 when they can't remember whether it's 54 or 56. Each of those is a real, high-volume search query — and most of the results are identical calculator widgets. So when I built Wrongulator , a calculator that returns a confidently wrong answer on purpose, I had a question worth asking: what if every expression were its own page, ranking for the exact arithmetic people already search? That is programmatic SEO — generating a page per parameter instead of writing pages by hand. And doing it across 17 languages means programmatic SEO with hreflang, where each generated page also declares its 16 translated siblings. The trap is that most programmatic surfaces are thin, duplicative, and get buried by Google. This one isn't, for a specific reason: every page has a real, unique answer baked into the HTML before any JavaScript runs. This post is about how — and the honest costs nobody mentions. Why a Permalink Per Expression Is Even Possible A page per expression only works if /2+2 reproduces the same result for everyone, forever, with no database behind it. That property isn't free — it's the result of one design decision I cover in detail in why a viral toy must be wrong the same way every time : the wrong answer is a pure function of the expression, seeded by a stable hash, with no per-user state. The relevant consequence here is what that property unlocks for SEO. Because f("2+2") always returns the same wrong answer, the server can compute that answer on demand for any expression in the URL, with zero storage. There's no pages table, no CMS, no pre-generation job. A request for /64+5 runs the engine, gets 67 ("the only correct number"), and renders a complete page around it. The programmatic surface is, in effect, infinite — but it costs nothing to hold, because nothing is stored. The pure function is what makes thousands of unique pages possible without a database. That's the foundation. Everything below is about
AI 资讯
Can IP Geolocation Personalise Content with Node.js?
A visitor lands on a website and immediately sees prices in the wrong currency, content written for another region, and shipping information that does not apply to them. Nothing is technically broken, yet the experience feels poorly designed. For international websites, location can be a useful personalization signal. Instead of asking every visitor to manually select a country before displaying relevant information, developers can use IP based geographic data as an initial indication of where a request originates. That is where ip geolocation for content personalisation can become useful. The objective is not to identify a person. It is to make an otherwise anonymous visit more contextually relevant. How can location improve content personalisation? Location can influence many small decisions that collectively affect the user experience. An ecommerce website may display a local currency. A news publisher may surface regional stories. A software company may show country specific documentation or availability information. The process is relatively simple. A visitor sends a request to a website. The server obtains the request's public IP address. That IP is sent to a geolocation service. The response provides geographic information. The application then selects content according to predefined rules. The crucial part is the final step. Geolocation provides data, but business logic determines what the visitor actually sees. Which approaches can websites use? One approach is manual location selection. The user chooses their country or region from a menu. This is transparent and usually accurate because the user explicitly provides the information. However, it adds friction and may be forgotten during future visits. Browser based location is another option. It can provide more precise positioning, but it normally requires permission and is not always appropriate for simple content personalization. IP based geolocation sits between these approaches. It requires no location