Chuyển đến nội dung chính

Bài 1: Node.js Architecture Deep Dive

V8 Engine, libuv, C++ bindings. Single-threaded event loop model. Node.js vs Deno vs Bun. Lịch sử phát triển, use cases. node --inspect, V8 flags.

💻 Lập trình — Bài 1 Bài 1: Node.js Architecture Deep Dive

Node.js Core: Từ Cơ bản đến Nâng cao

Phần 1: Node.js Internals

xdev.asia

1. Node.js là gì?

Node.js là một JavaScript runtime được xây dựng trên V8 Engine của Chrome, cho phép chạy JavaScript ở phía server. Ra đời năm 2009 bởi Ryan Dahl, Node.js đã thay đổi hoàn toàn cách thế giới nghĩ về JavaScript.

Thành phầnVai trò
V8 EngineBiên dịch JS → machine code, quản lý memory
libuvEvent loop, async I/O, thread pool, cross-platform
C++ BindingsKết nối JS với system-level APIs (fs, net, crypto)
Node.js APIJavaScript APIs (http, path, events, stream…)

2. Kiến trúc Node.js

┌─────────────────────────┐
│     Your JavaScript     │
├─────────────────────────┤
│     Node.js APIs        │
│  (http, fs, crypto…)    │
├─────────────────────────┤
│    C++ Bindings         │
├──────────┬──────────────┤
│  V8      │    libuv     │
│  Engine  │  (event loop)│
└──────────┴──────────────┘
│       Operating System       │

3. Node.js vs Deno vs Bun

FeatureNode.jsDenoBun
EngineV8V8JavaScriptCore
LanguageC++RustZig
TypeScript--experimental-strip-typesNativeNative
Package Managernpm/pnpm/yarndeno addbun install
EcosystemLớn nhất (3M+ packages)Tương thích npmTương thích npm
SecurityFull accessPermissionsFull access

4. Cài đặt & Thiết lập

# Cài Node.js qua nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
nvm install 22
nvm use 22
node --version  # v22.x.x

# Cài pnpm
corepack enable
corepack prepare pnpm@latest --activate

# Khởi tạo project
mkdir my-node-project && cd my-node-project
pnpm init

5. V8 Engine Flags

# Xem tất cả V8 flags
node --v8-options | head -50

# Giới hạn memory
node --max-old-space-size=4096 app.js

# Inspect debugger
node --inspect app.js        # Chrome DevTools tại chrome://inspect
node --inspect-brk app.js    # Break ở dòng đầu tiên

# V8 profiling
node --prof app.js
node --prof-process isolate-*.log > processed.txt

6. Hello World & REPL

// hello.ts
const message: string = 'Hello from Node.js!'
console.log(message)
console.log(`Node.js version: ${process.version}`)
console.log(`Platform: ${process.platform}`)
console.log(`Architecture: ${process.arch}`)
console.log(`PID: ${process.pid}`)
console.log(`Memory: ${JSON.stringify(process.memoryUsage())}`)
# Chạy TypeScript trực tiếp (Node.js 22+)
node --experimental-strip-types hello.ts

# Hoặc dùng tsx
npx tsx hello.ts

Bài tiếp theo: Event Loop & Async Patterns — phases, microtasks, macrotasks.