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

Node.js Working Mechanism

Node.js Working Mechanism

Node.js is a JavaScript runtime built on the Chrome V8 engine. It enables developers to write server-side code in JavaScript. Unlike traditional server-side technologies, Node.js adopts aEvent-drivenandnon-blocking I/Omodel, which makes it particularly suitable for handling highly concurrent network applications.

Core features

  1. single-threaded: Node.js uses a single thread to handle requests
  2. Event loop: concurrency is handled through an event-driven mechanism
  3. non-blocking I/O: I/O operations do not block the main thread
  4. Cross-platform: can run on Windows, Linux, macOS, and other systems

Node.js executes JavaScript code through the V8 engine, interacts with the operating system through the Node.js API, and handles asynchronous I/O operations through Libuv. The event loop and worker threads ensure the efficient, non-blocking nature of Node.js.


Architecture components of Node.js

The architecture of Node.js can be divided into the following main layers:

1. JavaScript layer

This is the layer developers interact with directly, including:

2. C++ bindings layer

This layer exposes low-level functionality to the JavaScript layer, including:

3. Underlying dependencies


Event loop mechanism

The core working mechanism of Node.js is theEvent loop, which is responsible for scheduling and executing all asynchronous operations.

Phases of the event loop

  1. timers: execute callbacks of setTimeout and setInterval
  2. pending callbacks: execute callbacks of system operations (such as TCP errors)
  3. idle, prepare: for internal use
  4. poll: retrieve new I/O events and execute associated callbacks
  5. check: execute callbacks of setImmediate
  6. close callbacks: execute callbacks of close events (such as socket.on('close'))

Example

// example: understanding event loop order

setTimeout

(

(

)

=>

console.

log

(

'timeout'

)

,

0

)

;

setImmediate

(

(

)

=>

console.

log

(

'immediate'

)

)

;

// output order may differ depending on when the event loop starts


Non-blocking I/O principle

I/O operations in Node.js are non-blocking, achieved through the following:

Workflow

  1. The application initiates an I/O request (such as reading a file)
  2. Node.js passes the request to libuv for processing
  3. libuv uses system-provided asynchronous interfaces (such as Linux's epoll)
  4. The main thread continues executing other tasks
  5. When the I/O completes, the callback function is placed in the event queue
  6. The event loop executes the callback at the appropriate phase


Single thread and multiple processes

Although Node.js is single-threaded, it can leverage multi-core CPUs in the following ways:

1. Child process (child_process)

Example

const

{

fork

}

=

require

(

'child_process'

)

;

const

child

=

fork

(

'child.js'

)

;

child.

on

(

'message'

,

(

msg

)

=>

{

  console.

log

(

'Message from child process:'

,

msg

)

;

}

)

;

child.

send

(

{

hello

:

'world'

}

)

;

2. Cluster mode (cluster)

Example

const

cluster

=

require

(

'cluster'

)

;

const

http

=

require

(

'http'

)

;

const

numCPUs

=

require

(

'os'

)

.

cpus

(

)

.

length

;

if

(

cluster.

isMaster

)

{

 

// the main process forks worker processes

 

for

(

let i

=

0

;

i

<

numCPUs

;

i

++

)

{

    cluster.

fork

(

)

;

 

}

}

else

{

 

// worker processes create an HTTP server

  http.

createServer

(

(

req

,

res

)

=>

{

    res.

writeHead

(

200

)

;

    res.

end

(

'Hello World\n'

)

;

 

}

)

.

listen

(

8000

)

;

}

3. Worker Threads

Example

const

{

Worker

}

=

require

(

'worker_threads'

)

;

const

worker

=

new

Worker

(

`

 

const

{

parentPort

}

=

require

(

'worker_threads'

)

;

  parentPort.

on

(

'message'

,

(

msg

)

=>

{

    console.

log

(

'Message received:'

,

msg

)

;

    parentPort.

postMessage

(

'Message received'

)

;

 

}

)

;

`

,

{

eval

:

true

}

)

;

worker.

on

(

'message'

,

(

msg

)

=>

{

  console.

log

(

'Reply from worker thread:'

,

msg

)

;

}

)

;

worker.

postMessage

(

'Main thread message'

)

;


Performance Optimization Suggestions

1. Avoid blocking the event loop

2. Use stream processing wisely

Example

// bad practice: reading a large file all at once

fs.

readFile

(

'bigfile.txt'

,

(

err

,

data

)

=>

{

 

// Process data

}

)

;

   

// good practice: using streams

const

stream

=

fs.

createReadStream

(

'bigfile.txt'

)

;

stream.

on

(

'data'

,

(

chunk

)

=>

{

 

// process data chunks

}

)

;

3. Connection pool management

4. Memory management


Frequently Asked Questions

Q: Is Node.js really single-threaded?

A: JavaScript execution is single-threaded, but Node.js uses multiple threads underneath (such as libuv's thread pool handling certain I/O operations).

Q: How to handle CPU-intensive tasks?

A: You can use Worker Threads, or split the task into smaller tasks and process them in batches via setImmediate.

Q: Why is Node.js suitable for I/O-intensive applications?

A: Because its non-blocking I/O model can handle other requests while waiting for I/O, without creating a new thread for each connection.


Summary

Node.js's working mechanism is based on the following core concepts:

  1. Event-driven programming model
  2. Non-blocking I/O operations
  3. Single-threaded but supports multi-process/multi-thread extension
  4. Efficient event loop scheduling

Understanding these mechanisms is crucial for writing high-performance Node.js applications. By making good use of its asynchronous features, you can build network applications capable of handling high concurrency.