Home  >  Article  >  Web Front-end  >  What does I/O mean in nodejs

What does I/O mean in nodejs

WBOY
WBOYOriginal
2022-03-04 15:37:532756browse

In nodejs, "I/O" means input and output, usually indicating "I/O" operations. "I/O" operations can be divided into single-threaded serial execution and multi-threaded parallel execution. , single-threaded installation is executed sequentially, any slowness in execution will cause subsequent execution code to block.

What does I/O mean in nodejs

The operating environment of this article: Windows 10 system, nodejs version 12.19.0, Dell G3 computer.

What does I/O mean in nodejs

Many people are familiar with the Nginx server. Nginx is written in pure C and is used as a web server and in reverse proxy. It has good advantages in terms of services such as load balancing and so on. Node and Nginx servers are similar in that they are event-driven.

JavaScript in the browser is executed on a single thread, and it also shares the same thread with UI rendering. When JavaScript is executed, UI rendering and response should be in a stagnant state. (If the script execution time exceeds 100 milliseconds, the user will feel the page is stuck). When encountering these situations, we will think of asynchronous methods to eliminate these waiting problems, and we will not introduce the concepts of asynchronous and synchronized.

Next, let’s take a closer look at the event-driven and non-blocking I/O characteristics of NodeJS. Understanding these will have more profound significance for us to better learn NodeJS development and build a high-performance Web platform.

1. Overview of I/O operations:

I/O operations are familiar to any developer. Now let’s briefly talk about NodeJS I.O operations. I/O operations are divided into: single-threaded serial execution; multi-threaded parallel execution. Both methods have their own advantages and disadvantages. The cost of multi-threading is the high cost of thread creation and thread context switching during execution, and multi-threading faces lock and state synchronization problems. Single-threaded installation is executed sequentially. Any slowness in execution will cause subsequent execution code to block. The description of the serial execution of tasks (conceptually similar to synchronous execution) and the parallel execution of tasks is as follows:

What does I/O mean in nodejs

Use a single thread in NodeJS to stay away from deadlocks , State synchronization issues, use asynchronous I/O to keep single threads away from blocking, so as to better use the CPU. Asynchronous I/O expects that I/O calls will no longer block subsequent operations, and allocate the original waiting time for I/O completion to other required businesses for execution.

Many times some developers are confused about the concepts of asynchronous/synchronous and blocking/non-blocking, and the two are not related. Blocking I/O means that after calling, you must wait until the system kernel level completes all operations before the call ends. Non-blocking I/O returns immediately after being called. Regarding blocking I/O and non-blocking I/O, there are the following diagrams:

What does I/O mean in nodejs

2. NodeJS asynchronous I/O analysis:

Event loop: When the process starts, Node will create a loop similar to while(true). The process of each execution of the loop body is called Tick. The process of each Tick is to check whether there is time to be processed.

Observers: There are one or more observers in each time loop. The process of judging whether there are events to be processed is to ask these observers whether there are more events to be processed.

Request object: In the transition process from JavaScript initiating a call to the kernel completing the I/O operation, there is an intermediate product, which is the request object.

I/O thread pool: Assemble the request, send it to the I/O thread pool to wait for execution, complete the first step of the I/O operation, and enter the second part of the callback notification. (In Windows, after the I/O operation in the thread pool is called, the obtained result will be stored in the req->result attribute, and then PostQueuedCompletionStatus() will be called to notify IOCP that the current object operation has been completed.)

Asynchronous I/O has the following figure:

What does I/O mean in nodejs

3. NodeJS asynchronous programming example:

Async I was introduced earlier /O related concepts, here is an example of asynchronous I/O operations:

var config = require('./config.json');
var fs = require("fs");
var http = require('http');
var url_module = require("url");
http.createServer(function (request, response) {
var key = url_module.parse(request.url).query.replace('key=', '');
switch (request.method) {
   case 'GET':  // Asynchronous Response Generation
       fs.readFile(config.dataPath + key, 'utf8', function(err, value) {
           if (err) {
               // Return File Not Found if file hasn't yet been created
               response.writeHead(404, {'Content-Type': 'text/plain'});
               response.end("The file (" + config.dataPath + key + ") does not yet exist.");
           } else {
               // If the file exists, read it and return the sorted contents
               var sorted = value.split(config.sortSplitString).sort().join('');
               response.writeHead(200, {'Content-Type': 'text/plain'});
               response.end(sorted);
           }
       });
       break;
   case 'POST':  // Synchronously append POSTed data to a file
       var postData = '';
       request
           .on('data', function (data) {
               postData += data;
           })
           .on('end', function () {
               fs.appendFile(config.dataPath + key, postData, function(err) {
                   if (err) {
                       //  Return error if unable to create/append to the file
                       response.writeHead(400, {'Content-Type': 'text/plain'});
                       response.end('Error: Unable to write file: ' + err);
                   } else {
                       //  Write or append posted data to a file, return "success" response
                       response.writeHead(200, {'Content-Type': 'text/plain'});
                       response.end('success');
                   }
               });
           });
       break;
   default:
       response.writeHead(400, {'Content-Type': 'text/plain'});
       response.end("Error: Bad HTTP method: " + request.method);
}
}).listen(config.serverPort);
console.log('synchronous server is running: ', config.serverPort);

Recommended learning: "nodejs video tutorial"

The above is the detailed content of What does I/O mean in nodejs. For more information, please follow other related articles on the PHP Chinese website!

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