search
HomeWeb Front-endJS TutorialAn in-depth analysis of the Node.js event loop_node.js

Node.js is a single-process, single-threaded application, but supports concurrency through events and callbacks, so its performance is very high.

(Source: Javascript is single-threaded and asynchronous, but these languages ​​​​have a common feature: they are event-driven. The events that drive them come from a heterogeneous platform.)

Every API in Node.js is asynchronous and runs as a separate thread, uses asynchronous function calls, and handles concurrency.

Basically all event mechanisms in Node.js are implemented using the observer pattern in the design pattern.

Node.js single thread is similar to entering a while(true) event loop until no event observer exits. Each asynchronous event generates an event observer. If an event occurs, the callback function is called.

Event-driven model

Node.js uses an event-driven model. When the webserver receives a request, it closes it and processes it, and then serves the next web request.

When this request is completed, it is put back into the processing queue, and when the beginning of the queue is reached, the result is returned to the user.

This model is very efficient and scalable because the webserver always accepts requests without waiting for any read or write operations.
(This is also called non-blocking IO or event-driven IO)

In the event-driven model, a main loop is generated to listen for events and trigger a callback function when an event is detected.

This is how the entire event-driven process is implemented, which is very simple. Somewhat similar to the observer pattern, the event is equivalent to a subject (Subject), and all handler functions registered to this event are equivalent to observers (Observer).

Node.js has multiple built-in events. We can bind and listen to events by introducing the events module and instantiating the EventEmitter class, as shown in the following example:

//引入events模块
var events = require('events');
//创建eventEmitter对象
var eventEmitter = new events.EventEmitter();
//创建事件处理程序
var connectHandler = function connected() {
 console.log('连接成功。');
 //触发data_received事件 
 eventEmitter.emit('data_received');
}
//绑定connection事件处理程序
eventEmitter.on('connection', connectHandler);
//使用匿名函数绑定data_received事件
eventEmitter.on('data_received', function(){
 console.log('数据接收成功。');
});
//触发connection事件 
eventEmitter.emit('connection');
console.log("程序执行完毕。"); 

The output result of the above code is:

Connection successful.

Data received successfully.

The program execution is completed.

The above results are just as you think. Through this event-driven model, we can achieve asynchronous operations.

(For example, we can read the file while executing other commands. After the file reading is completed, we return the file content as a parameter of the callback function. This way there is no blocking or waiting for file I/O while executing the code Operation. This greatly improves the performance of Node.js and can handle a large number of concurrent requests)
.

var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
 if (err){
 console.log(err.stack);
 return;
 }
 console.log(data.toString());
});
console.log("程序执行完毕。"); 

The output result of the above code is:

The program execution is completed.

Contents of input.txt.

From the above code, we can see that fs.readFile can distribute events. Of course, many objects in Node.js will distribute events. A net.Server object will also distribute an event every time there is a new connection. All of these generate Event objects are instances of events.EventEmitter.

But most of the time we don’t use EventEmitter directly, but inherit it in the object. Including fs, net, http, as long as the core modules that support event response are subclasses of EventEmitter.

Why do you do this? There are two reasons:

First of all, the event implementation of an object with a certain entity function conforms to the semantics. The monitoring and emission of events should be methods of an object.
Secondly, the object mechanism of JavaScript is based on prototype and supports partial multiple inheritance. Inheriting EventEmitter will not disrupt the original inheritance relationship of the object.

Let me share with you my first NodeJs project

There are usually two ways to install Node.js: compiling the source code yourself and using compiled files. I use compiled files here
Currently, I have the node-v4.2.3-linux-x64 I just downloaded in my home directory

1. First decompress

Copy code The code is as follows:

tar xvf node-v4.2.3-linux-x64

2. Set the link. The purpose of setting the link is that the node command can be used in any path

Copy code The code is as follows:

ln -s /home/node-v4.2.3-linux-x64/bin/node /usr/local/bin/node
ln -s /home/node-v4.2.3-linux-x64/bin/npm /usr/local/bin/npm

3. Create a directory called mynodeproj under the home folder, and then create a file called server.js (of course you can also name it another way)

var http = require('http');
http.createServer(function (request, response) {
 //发送 HTTP 头部 
 //HTTP 状态值: 200 : OK
 //内容类型: text/plain
 response.writeHead(200, {'Content-Type': 'text/plain'});
 //发送响应数据 "Hello World"
 response.end('Hello World\n');
}).listen(8888);
//终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/'); 

4. Use the node command to execute the above code

node server.js

After executing the above command, "Server runnint at http://127.0.0.1:8888/" will be displayed on the command line, which means that the program has been executed successfully!

Because my server is running in Alibaba Cloud, I can access it by just typing Alibaba Cloud IP + port in an external browser.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.