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

Lesson 1: Node.js Architecture Deep Dive

V8 Engine, libuv, C++ bindings. Single-threaded event loop model. Node.js vs Deno vs Bun. Development history, use cases. node --inspect, V8 flags.

💻 Programming — Lesson 1 Lesson 1: Node.js Architecture Deep Dive

Node.js Core: From Basics to Advanced

Part 1: Node.js Internals

xdev.asia

1. What is Node.js?

Node.js is a JavaScript runtime built on Chrome's V8 Engine, allowing to run JavaScript on the server side. Launched in 2009 by Ryan Dahl, Node.js has completely changed the way the world thinks about JavaScript.

IngredientsRole
V8 EngineJS compilation → machine code, memory management
libuvEvent loop, async I/O, thread pool, cross-platform
C++ BindingsConnect JS to system-level APIs (fs, net, crypto)
Node.js APIJavaScript APIs (http, paths, events, streams…)

2. Node.js architecture

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

3. Node.js vs Deno vs Bun

FeaturesNode.jsDenoBun
EngineV8V8JavaScriptCore
LanguageC++RustZig
TypeScript--experimental-strip-typesNativeNative
Package Managernpm/pnpm/yarndeno addbun install
EcosystemLargest (3M+ packages)npm compatiblenpm compatible
SecurityFull accessPermissionsFull access

4. Installation & Setup

# 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

Next article: Event Loop & Async Patterns — phases, microtasks, macrotasks.