慣性聚合 高效追讀感興趣之博客、新聞、科技資訊
閱原文 以慣性聚合開啟

推薦訂閱源

博客园 - 司徒正美
V
V2EX
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
月光博客
月光博客
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
WordPress大学
WordPress大学
酷 壳 – CoolShell
酷 壳 – CoolShell
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python)
Node.js 事件循环架构——单线程运行时如何处理海量并发
Raj Dutta · 2026-05-24 · via DEV Community

初涉Node.js,吾心有惑:

独线程之系,何以同刻应千请?

似相悖,然既明事件循环之理(尤赖官文),豁然开朗。此篇,吾欲以最简之辞,释其深蕴,不堕浅薄。


何谓“单线程”

Node.js常被称为单线程然此言不备。

  • JavaScript之执行,行于一主线程
  • 然Node.js其物也非不限于一时一事
  • 其用之:

    • 操作系统核心
    • 后台线程(libuv)
    • 异步输入输出

故正确之言曰:

Node.js也单线程以执行JavaScript然则多系統處理輸出入

此别乃一切之本。


核心理念:事件驱动,非阻塞架构

Node.js不待诸务毕

其法若此:

  1. 受请
  2. 始务(呼DB、读檄、询API)
  3. 不待
  4. 迁次请
  5. 俟果备而归

是谓之非阻塞 I/O.

→ 据官方文档载:
Node.js 每当可能,皆将操作委诸系统,故主线程得以清闲.


想象之如次(简易譬喻)

试想:

  • 汝为侍者(事件循环)
  • 庖厨 = 操作系统 / 后台工作者

汝:

  • 奉令
  • 达庖厨
  • 进成馔

尔毋:

  • 自庖
  • 虚候一令

此即Node.js之扩也


深探:事件循环之序

事件循环非独列次。其行于 各司其职,分理各类回调。

架构:

主要阶段:

  1. 计时器
  • 执行setTimeout()setInterval()
  1. 中的回调
  • 处理系统级回调(如TCP错误)
  1. 闲置/准备
  • 内部使用(非我们所处理之事)
  1. 投票阶段(至要)
  • 索新I/O之变
  • 行I/O之回调
  • 若无事则待
  1. 检视阶段
  • setImmediate()之回调
  1. 闭回调
  • 行清理之回调(如socket.on('close')
   ┌───────────────────────────┐
   │           timers          │
   └─────────────┬─────────────┘
                 │
                 v
   ┌───────────────────────────┐
┌─>│     pending callbacks     │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │       idle, prepare       │
│  └─────────────┬─────────────┘      ┌───────────────┐
│  ┌─────────────┴─────────────┐      │   incoming:   │
│  │           poll            │<─────┤  connections, │
│  └─────────────┬─────────────┘      │   data, etc.  │
│  ┌─────────────┴─────────────┐      └───────────────┘
│  │           check           │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │      close callbacks      │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
└──┤           timers          │
   └───────────────────────────┘

入全屏模式 退出全屏模式

→ 此循环持续流转不息.


询相为心

此乃玄妙之境.

  • 来者之请于此处理.
  • 既成之务复归于此.
  • 若无待办之事 → 节点从容而待.

故 Node.js 不费 CPU 之循环,而能久持其可扩展之性。


process.nextTick() 與 setImmediate() 之辨

此乃微末而甚要之节,世人多所忽焉。

process.nextTick()

  • 施行之方今之职既毕,即行后事。
  • 驰骋事毕而轮回复始
  • 若滥用,可阻塞I/O

setImmediate()

  • 次迭代中执行(检视阶段)
  • 更安全,更可预期

→ 官方文档建议:

多场景下优先选用setImmediate()


Node.js如何处理千钧之请

此诚要问也.

传统服务器(每请求一线程)

  • 每请求数起一缕丝
  • 内存之重
  • 上下文切换之劳

节点之道

  • 单丝应万求
  • 每求不生丝
  • 以异步回响代之

实际之状:

  • 千客叩门
  • 节点云:

    • 悉录诸请
    • 启诸务之异步
    • 使事件之循环无滞
  • 既得应答:

    • 回呼次第列于序
    • 事件之循环施之

→ 果:
高并发而资源之用寡


要义:Node.js最宜于I/O之务

Node.js 之辉发于:

  • 数据库查询
  • API调用
  • 文件系统操作
  • 流式传输
  • 实时应用(如聊天、套接字)

然…

非其所长:

  • 繁重CPU计算
  • 大型同步循环

盖因:

阻塞事件循环 = 阻塞一切


害事之谬,损功之由

1. 阻塞之码

while(true) {}

入全景模式 出全屏模式

→ 整體伺服器凍結


二、误用process.nextTick()

  • 可饿其事绪
  • 阻隔输入输出之执行

三、于 API 中著同步之码

fs.readFileSync()

Enter fullscreen mode Exit fullscreen mode

→ 避之於生产


若需更大力(超越一核之扩展)

Node.js 每进程单线程,然可藉以下之法以扩展之:

  • 集群模块
  • 工作线程
  • 负载均衡器

→ 允此:

  • 多核之用
  • 横轴扩展

吾之终悟

阅官方Node.js之文,亲历筑应用,吾之思若此:

  • Node.js非求一时之功也
  • 彼正欲之莫阻。

事件循环者,不过为聪慧之协调者也。

  • 其行所备也
  • 越待而逝
  • 使系统运行不息

是故也。

Node.js能应数千并请求——非并行执行,而以高效调度与无阻塞设计


终章

若必以一言蔽之

Node.js之可扩展,非因其速,而因其优。不待无谓

一旦此心法通,Node.js之架构,无不明矣。