Node.js has better performance, so it is often seen in use, so this article will explain it in detail.
Node.js is a single-process, single-threaded application, but supports concurrency through events and callbacks, so its performance is very high.
Every API in Node.js is asynchronous and runs as a separate thread, uses asynchronous function calls, and handles concurrency.
Node.js Basically all event mechanisms 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 program
Node.js uses the event-driven model. When the web server receives a request, it closes it and processes it, and then serves the next web request.
When the 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 a callback function is triggered when an event is detected.
The entire event-driven process is implemented in this way, 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(); 以下程序绑定事件处理程序: // 绑定事件及事件的处理程序eventEmitter.on('eventName', eventHandler); 我们可以通过程序触发事件: // 触发事件eventEmitter.emit('eventName');
Example
Create the main.js file, the code is as follows:
// 引入 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("程序执行完毕。");
Next let us execute the above code:
$ node main.js connection is successful. Data received successfully. The program execution is completed.
How does Node application work?
In Node applications, functions that perform asynchronous operations take the callback function as the last parameter, and the callback function receives the error object as the first parameter.
Next, let us re-look at the previous example and create an input.txt. The file content is as follows:
Official website address of the rookie tutorial: www.runoob.com
Create the main.js file with the following code:
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 above introduces the use of Node.js in detail. If you want to know more related knowledge, please pay attention to the php Chinese website.
Related recommendations:
Detailed explanation of the principle of port reuse in Node.Js
What are the registration email activations for Node.js Method
How Node.Js implements Bitcoin address
The above is the detailed content of About the use of Node.js time loop. For more information, please follow other related articles on the PHP Chinese website!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
