Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js Fundamental Concepts

Node.js Fundamental Concepts

Node.js is a JavaScript runtime environment built on the Chrome V8 JavaScript engine. Simply put, Node.js allows JavaScript to run on the server side, not just in the browser.

Core Features of Node.js

1. Single-Threaded Event Loop

2. Non-Blocking I/O

3. Cross-Platform

4. Rich Ecosystem


Differences from Traditional Server-Side Technologies

1. Traditional server-side technologies (such as Apache + PHP):



请求1 → 创建线程1 → 处理请求 → 返回响应 → 销毁线程1

请求2 → 创建线程2 → 处理请求 → 返回响应 → 销毁线程2

请求3 → 创建线程3 → 处理请求 → 返回响应 → 销毁线程3

2. The Node.js approach:



请求1 → 事件循环 → 处理请求 → 返回响应

请求2 → 事件循环 → 处理请求 → 返回响应  (复用同一线程)

请求3 → 事件循环 → 处理请求 → 返回响应

Feature Traditional Multithreaded Model Node.js Single-Threaded Model
Memory Usage Each thread occupies about 2MB Single-threaded, low memory usage
Concurrency Handling The number of threads limits concurrency The event loop handles high concurrency
Context Switching Frequent thread-switching overhead No thread-switching overhead
Programming Complexity Need to handle thread synchronization Avoids locks and thread synchronization issues
Applicable scenarios CPU-Intensive Tasks I/O-Intensive Tasks

Application Scenarios of Node.js

1. Suitable Application Scenarios

Web Applications

Real-Time Applications

Microservice architecture

Tools and Command-Line Applications

Internet of Things (IoT) Applications

2. Unsuitable Application Scenarios

CPU-Intensive Tasks

Applications requiring heavy computation


Event-Driven and Non-Blocking I/O Model

Example of a Traditional Blocking I/O Model:

Example

// Pseudocode - blocking operation

// Each readFileSync "blocks" the program, waiting for the file read to finish before continuing

const

data1

=

readFileSync

(

'file1.txt'

)

;

 

// The program pauses here, waiting for the read to complete

const

data2

=

readFileSync

(

'file2.txt'

)

;

 

// After data1 is read, pause and wait again

const

data3

=

readFileSync

(

'file3.txt'

)

;

 

// After data2 is read, pause and wait again

console.

log

(

'All files read complete'

)

;

         

// This point is reached only after all three files have been read

// Total time = time to read file1 + time to read file2 + time to read file3

Example of the Node.js Non-Blocking I/O Model:

Example

// Node.js asynchronous operation

const

fs

=

require

(

'fs'

)

;

// The three file-read operations are issued almost simultaneously, and the program does not wait for any of them to complete

fs.

readFile

(

'file1.txt'

,

(

err

,

data1

)

=>

{

   

// This callback function is called automatically after file1.txt has been read

    console.

log

(

'File 1 read complete'

)

;

}

)

;

fs.

readFile

(

'file2.txt'

,

(

err

,

data2

)

=>

{

   

// This callback function is called automatically after file2.txt has been read

    console.

log

(

'File 2 read complete'

)

;

}

)

;

fs.

readFile

(

'file3.txt'

,

(

err

,

data3

)

=>

{

   

// This callback function is called automatically after file3.txt has been read

    console.

log

(

'File 3 read complete'

)

;

}

)

;

// Note: this line executes first! Because the three file-read operations above are asynchronous,

// after issuing the read requests, the program immediately continues and does not wait for the reads to complete

console.

log

(

'Program continues execution, not waiting for file reads'

)

;

// Example of actual output order:

// Program continues execution, not waiting for file reads ← printed first

// File 2 read complete ← whichever file finishes first prints first; order is not fixed

// File 1 read complete

// File 3 read complete

// Total time ≈ the time of the slowest of the three files to read (concurrent execution, not sequential addition)

The Event Loop Mechanism:

The event loop is the core mechanism that enables non-blocking I/O in Node.js. It runs continuously, constantly checking for pending tasks, thereby achieving "single-threaded handling of concurrency":

  1. Call Stack: Executes synchronous code; functions are pushed onto the stack when called and popped off when finished
  2. Event Queue: Stores callback functions after asynchronous operations complete, waiting for the call stack to be idle before executing them in order
  3. Event Loop: Continuously monitors the call stack and event queue; once the call stack is empty, it takes callbacks from the event queue and puts them on the call stack for execution

The event loop processes the following phases in a fixed order:



┌───────────────────────────┐

┌─>│           timers          │  ← 执行 setTimeout、setInterval 的到期回调

│  └─────────────┬─────────────┘

│  ┌─────────────┴─────────────┐

│  │     pending callbacks     │  ← 执行上一轮循环中延迟的 I/O 回调(如某些系统错误回调)

│  └─────────────┬─────────────┘

│  ┌─────────────┴─────────────┐

│  │       idle, prepare       │  ← Node.js 内部使用,开发者一般不需要关心

│  └─────────────┬─────────────┘

│  ┌─────────────┴─────────────┐

│  │           poll            │  ← 核心阶段:获取新的 I/O 事件并执行其回调(如文件读取、网络请求完成)

│  └─────────────┬─────────────┘

│  ┌─────────────┴─────────────┐

│  │           check           │  ← 执行 setImmediate 的回调(在 poll 阶段之后立即执行)

│  └─────────────┬─────────────┘

│  ┌─────────────┴─────────────┐

└──┤      close callbacks      │  ← 执行关闭事件的回调,如 socket.on('close', ...)

   └───────────────────────────┘

For beginners, the most important thing to remember is:Synchronous code is always executed first, while asynchronous callbacks (such as file-read completion handlers) are executed only after the call stack is empty.


The JavaScript Runtime Environment

Introduction to the V8 Engine

V8 is a high-performance JavaScript engine developed by Google and is also the core component of the Chrome browser.

Node.js uses the V8 engine to execute JavaScript code.

Features of the V8 Engine:

Just-in-Time Compilation (JIT)

Garbage Collection

Optimization Techniques

Browser JavaScript vs Node.js JavaScript

Although both use the JavaScript language, differences in the runtime environment lead to some important distinctions:

Similarities:

Differences:

Feature Browser JavaScript Node.js JavaScript
The Global Object window global
Module System ES6 modules, AMD CommonJS, ES6 modules
File system access not accessible (due to security restrictions) full access
Network requests XMLHttpRequest, Fetch http, https modules
DOM Manipulation supported (for manipulating page elements) not supported (no page on the server side)
Process control Not supported supported (can read environment variables, exit the process, etc.)

Browser Environment Example:

Example

// Global objects and DOM operations in the browser

console.

log

(

window

)

;

                     

// The browser global object, containing all browser APIs

document.

getElementById

(

'app'

)

;

         

// Get a page element by ID (not available in Node.js)

localStorage.

setItem

(

'key'

,

'value'

)

;

   

// Browser local storage (not available in Node.js)

Node.js Environment Example:

Example

// Global objects and file operations in Node.js

console.

log

(

global

)

;

                             

// The Node.js global object (corresponding to window in the browser)

const

fs

=

require

(

'fs'

)

;

                       

// Import the built-in file system module (not available in the browser)

fs.

readFile

(

'data.txt'

,

'utf8'

,

callback

)

;

       

// Read a local file on the server (not available in the browser)

Differences in Global Objects

Global Objects in the Browser:

Example

// Browser environment

console.

log

(

this

===

window

)

;

 

// true; the top-level this is the window object

var

globalVar

=

'hello'

;

console.

log

(

window.

globalVar

)

;

 

// 'hello'; variables declared with var become properties of window

Global Objects in Node.js:

Example

// Node.js environment

// Note: in Node.js, every file is an independent module, and this inside a module is not equal to global

console.

log

(

this

===

global

)

;

 

// false (in module scope, this points to module.exports)

var

globalVar

=

'hello'

;

console.

log

(

global.

globalVar

)

;

 

// undefined; variables inside a module are not automatically attached to global

// Module scope in Node.js

console.

log

(

this

)

;

 

// {} empty object, the initial value of module.exports

console.

log

(

module.

exports

===

this

)

;

 

// true; inside a module, this points to module.exports

** Global Variables Specific to Node.js:**

Example

console.

log

(

__dirname

)

;

 

// The absolute path of the directory containing the current module, e.g., /home/user/project

console.

log

(

__filename

)

;

 

// The absolute path of the current module file, e.g., /home/user/project/app.js

console.

log

(

process

)

;

   

// The process object, which can read command-line arguments (process.argv), environment variables (process.env), etc.

console.

log

(

Buffer

)

;

     

// A constructor for handling binary data, commonly used in file I/O and network communication


Advantages and Limitations of Node.js

Detailed Advantages

1. High Concurrency Handling

A traditional multithreaded server needs about 20GB of memory to handle 10,000 concurrent connections (about 2MB per thread), while Node.js needs very little memory to handle the same number of connections.

Example

// Node.js high concurrency example

const

http

=

require

(

'http'

)

;

const

server

=

http.

createServer

(

(

req

,

res

)

=>

{

   

// Simulate an asynchronous operation (such as a database query), returning a response after 100ms

   

// During these 100ms, the event loop can continue processing other requests without being blocked

    setTimeout

(

(

)

=>

{

        res.

writeHead

(

200

,

{

'Content-Type'

:

'text/plain'

}

)

;

        res.

end

(

'Hello World\n'

)

;

   

}

,

100

)

;

}

)

;

server.

listen

(

3000

,

(

)

=>

{

    console.

log

(

'Server running at http://localhost:3000/'

)

;

}

)

;

// Thanks to non-blocking I/O and the event loop, this server can handle thousands of requests simultaneously without blocking

2. Rapid Development

A unified JavaScript language stack (JavaScript for both front end and back end) makes front-end and back-end development more efficient. Developers only need to master one language to write both front-end and back-end code, and can share code logic between the two:

Example

// The same validation logic can be reused on both front end and back end, with no need to write it twice

function

validateEmail

(

email

)

{

   

const

regex

=

/^[^\s@]+@[^\s@]+.[^\s@]+$/

;

   

return

regex.

test

(

email

)

;

}

// Front-end use (running in the browser): when a user submits a form, validate on the front end first to avoid sending invalid requests to the server

if

(

validateEmail

(

userInput

)

)

{

   

// If validation passes, send to the server

}

// Back-end use (running in Node.js): the server validates again to prevent bypassing the front end and calling the API directly

if

(

validateEmail

(

req.

body

.

email

)

)

{

   

// If validation passes, save to the database

}

3. Advantages of a Unified Language Stack

4. Rich npm Ecosystem



# npm provides millions of open-source packages, almost any functionality can be found in a ready-made library

npm search express     # 搜索名为 express 的包

npm install express    # 安装 express 包到当前项目

npm update            # 更新当前项目中所有包到最新兼容版本

Analysis of Limitations

1. Performance Issues with CPU-Intensive Tasks

Example

// Bad example: a CPU-intensive task blocks the event loop

// fibonacciSync is a pure computation task that keeps the CPU occupied, during which the event loop cannot process other requests

function

fibonacciSync

(

n

)

{

   

if

(

n

<

2

)

return

n

;

   

return

fibonacciSync

(

n

1

)

fibonacciSync

(

n

2

)

;

}

// This blocks the entire application for several seconds, during which no requests can be responded to

console.

log

(

fibonacciSync

(

40

)

)

;

// Solution: use Worker Threads to run CPU-intensive tasks in a separate thread,

// so the event loop of the main thread is not blocked

const

{

Worker

,

isMainThread

,

parentPort

,

workerData

}

=

require

(

'worker_threads'

)

;

if

(

isMainThread

)

{

   

// Main thread: create a Worker and pass it the parameter { n: 40 }

   

// The Worker executes this current file in a separate thread (__filename refers to the current file path)

   

const

worker

=

new

Worker

(

__filename

,

{

        workerData

:

{

n

:

40

}

   

}

)

;

   

   

// Listen for messages (computation results) sent by the Worker

    worker.

on

(

'message'

,

(

result

)

=>

{

        console.

log

(

'Result:'

,

result

)

;

 

// After the Worker finishes computing, the main thread receives the result here

   

}

)

;

}

else

{

   

// Worker thread: get the parameters passed by the main thread via workerData, perform the computation, and send the result

   

const

result

=

fibonacciSync

(

workerData.

n

)

;

    parentPort.

postMessage

(

result

)

;

 

// Send the result back to the main thread

}

2. Callback Hell

Example

// Callback hell example: when multiple asynchronous operations need to run sequentially, callbacks keep nesting and code readability becomes very poor

fs.

readFile

(

'file1.txt'

,

(

err

,

data1

)

=>

{

   

if

(

err

)

throw

err

;

    fs.

readFile

(

'file2.txt'

,

(

err

,

data2

)

=>

{

 

// First level of nesting

       

if

(

err

)

throw

err

;

        fs.

readFile

(

'file3.txt'

,

(

err

,

data3

)

=>

{

 

// Second level of nesting

           

if

(

err

)

throw

err

;

           

// In real projects, such nesting can be a dozen levels deep, seriously affecting code maintainability

            console.

log

(

'All files read complete'

)

;

       

}

)

;

   

}

)

;

}

)

;

// Modern solution: use Promise + async/await to make asynchronous code as intuitive to write as synchronous code

const

fsPromises

=

require

(

'fs'

)

.

promises

;

async

function

readFiles

(

)

{

   

try

{

       

// await waits for each file read to complete, but the whole function does not block the event loop

       

// Note: this is sequential reading; to read multiple files concurrently, you can use Promise.all()

       

const

data1

=

await fsPromises.

readFile

(

'file1.txt'

)

;

       

const

data2

=

await fsPromises.

readFile

(

'file2.txt'

)

;

       

const

data3

=

await fsPromises.

readFile

(

'file3.txt'

)

;

        console.

log

(

'All files read complete'

)

;

   

}

catch

(

err

)

{

       

// try/catch can handle all asynchronous errors uniformly, with no need to check separately in each callback

        console.

error

(

'Failed to read file:'

,

err

)

;

   

}

}

3. Fragility of Single-Threading

Example

// An uncaught exception causes the entire Node.js process to crash

// Unlike multithreading, in a single thread one unhandled error stops the entire service

setTimeout

(

(

)

=>

{

   

throw

new

Error

(

'Uncaught exception'

)

;

 

// This causes the entire application to crash, and no requests can be responded to

}

,

1000

)

;

// Solution: register global exception handlers to log and exit gracefully before the application crashes

process.

on

(

'uncaughtException'

,

(

err

)

=>

{

    console.

error

(

'Uncaught exception:'

,

err

)

;

   

// Here you should log the error first and then exit, to avoid silent crashes that are hard to diagnose

    process.

exit

(

1

)

;

 

// Exit code 1 indicates an abnormal exit

}

)

;

process.

on

(

'unhandledRejection'

,

(

reason

,

promise

)

=>

{

   

// Triggered when a Promise is rejected but not handled by .catch()

    console.

error

(

'Unhandled Promise rejection:'

,

reason

)

;

    process.

exit

(

1

)

;

}

)

;


Analysis of Applicable Scenarios

1. RESTful API Services

Example

// Build a RESTful API service using the Express framework

// First install express: npm install express

const

express

=

require

(

'express'

)

;

const

app

=

express

(

)

;

app.

use

(

express.

json

(

)

)

;

 

// Middleware: automatically parse JSON data in the request body

// GET request: get the user list (corresponds to HTTP method GET, path /api/users)

app.

get

(

'/api/users'

,

(

req

,

res

)

=>

{

   

const

users

=

[

       

{

id

:

1

,

name

:

'Zhang San'

}

,

       

{

id

:

2

,

name

:

'Li Si'

}

   

]

;

    res.

json

(

users

)

;

 

// Return data in JSON format

}

)

;

// POST request: create a new user (the client passes user information in the request body)

app.

post

(

'/api/users'

,

(

req

,

res

)

=>

{

   

const

newUser

=

req.

body

;

         

// Get the JSON data sent by the client

   

// In real projects, user information is usually saved to a database here

    res.

status

(

201

)

.

json

(

{

message

:

'User created successfully'

,

user

:

newUser

}

)

;

}

)

;

// PUT request: update a specified user (:id is a route parameter; e.g., /api/users/1 means update the user with ID 1)

app.

put

(

'/api/users/:id'

,

(

req

,

res

)

=>

{

   

const

{

id

}

=

req.

params

;

       

// Get the user ID from the path

   

const

updatedData

=

req.

body

;

     

// Get the update content from the request body

    res.

json

(

{

message

:

`User $

{

id

}

Update successful`

,

data

:

updatedData

}

)

;

}

)

;

// DELETE request: delete a specified user

app.

delete

(

'/api/users/:id'

,

(

req

,

res

)

=>

{

   

const

{

id

}

=

req.

params

;

    res.

json

(

{

message

:

`User $

{

id

}

Delete successful`

}

)

;

}

)

;

app.

listen

(

3000

,

(

)

=>

{

    console.

log

(

'API server running at http://localhost:3000/'

)

;

}

)

;

2. Real-Time Applications

Example

// WebSocket real-time chat (using the socket.io library)

// First install: npm install socket.io

const

io

=

require

(

'socket.io'

)

(

server

)

;

// Listen for client connection events; triggered each time a new user connects

io.

on

(

'connection'

,

(

socket

)

=>

{

   

// Listen for the 'chat message' event sent by the currently connected client

    socket.

on

(

'chat message'

,

(

msg

)

=>

{

        io.

emit

(

'chat message'

,

msg

)

;

 

// Broadcast the message to all online clients (including the sender)

   

}

)

;

}

)

;

** 3. Middleware and Proxy Services**

Example

// HTTP reverse proxy server example

// Forward /api/xxx requests from the front end to the real back-end API server, hiding the real address; commonly used to solve cross-origin issues

// First install: npm install http-proxy-middleware

const

httpProxy

=

require

(

'http-proxy-middleware'

)

;

const

proxy

=

httpProxy

(

{

    target

:

'http://api.example.com'

,

 

// The real back-end API server address

    changeOrigin

:

true

,

               

// Change the Host in the request header to the target address

    pathRewrite

:

{

       

'^/api'

:

''

                   

// Remove the /api prefix from the path before forwarding, e.g., /api/users → /users

   

}

}

)

;