Home > Web Front-end > JS Tutorial > How Node.js code executes

How Node.js code executes

php中世界最好的语言
Release: 2018-03-12 17:08:23
Original
1679 people have browsed it

This time I will bring you the execution principle of Node.js code, what are the precautions for Node.js code execution, the following is a practical case, let's take a look.

After any software is successfully downloaded and installed, it is actually just a bunch of machine code, stored in the hard drive of our computer, that is, a bunch of exe files that we can see. Of course, some software is more It is large and may come with a bunch of dll files.

We have two ways to execute this software:

Most software, such as QQ, Feiqiu, and Chrome browser, can be executed and run by double-clicking it.

Some software needs to be run on the command line, such as our node.js.

When a software is executed, our operating system will create a corresponding process. It can be understood that the process is living software.

Processes and Threads

The core of the computer is the CPU, which undertakes all computing tasks. It is like a factory, running all the time. Assuming that the factory's power is limited, it can only be used by one workshop at a time. In other words, when one workshop starts working, other workshops must stop working. The meaning behind it is that a single CPU can only run one task at a time. The process is like the workshop of a factory. It represents a single task that the CPU can handle. At any time, the CPU is always running one process, and other processes are in a non-running state. In a workshop, there can be many workers who work together to complete a task. Threads are like workers in a workshop. A process can include multiple threads. The space in the workshop is shared by workers. For example, many rooms can be entered and exited by every worker. This means that the memory space of a process is shared, and each thread can use these shared memories. However, the size of each room is different. Some rooms can accommodate at most one person, such as the toilet. When there is someone in it, other people cannot enter. This means that when a thread uses some shared memory, other threads must wait for it to finish before they can use this memory.
A simple way to prevent others from entering is to add a lock at the door. People who arrive first lock the door. People who arrive later see the lock and line up at the door. They wait for the lock to open before going in. This is called a mutual exclusion lock. .

WhyJavaScript is single-threaded?

A major feature of the JavaScript language is single-threading, which means that it can only do one thing at a time. So why can't JavaScript have multiple threads? This can improve efficiency.

The single thread of JavaScript is related to its purpose. As a browser scripting language, JavaScript's main purpose is to interact with users and manipulate the DOM. This determines that it can only be single-threaded, otherwise it will cause very complex synchronization problems. For example, assume that JavaScript has two threads at the same time. One thread adds content to a certain DOM node, and the other thread deletes this node. In this case, which thread should the browser use?

So, in order to avoid complexity, JavaScript has been single-threaded since its birth. This has become the core feature of this language and will not change in the future.

JavaScript is single-threaded. Although there are workers, clusters, etc. that can implement multi-threading, these are used to create threads with limited functions and are still controlled by the main thread. Therefore, we think JavaScript It is single threaded.

In addition, we need to understand that JavaScript is single-threaded, which does not mean that Node.js is also single-threaded. After Node.js runs an instance, it is single-process and multi-threaded. There is a thread in it. The V8 engine is responsible for parsing JavaScript, and some threads are responsible for libuv, which is what we understand as the event loop.

How to understand IO:

I represents input, input: such as reading a file, initiating an ajax request for data
O represents output, output: such as writing a file

Synchronous vs asynchronous

Like the following, which does not involve reading and writing files, network requests, timers, all are synchronous codes:

var a = 1;var b = 2;function fn(){}
Copy after login

Like the following are all asynchronous codes:

fs.readFile('./a.js',callback);
fs.writeFile('./b.js',callback);
Copy after login

Including a bunch of mouse, keyboard events, ajax, etc. that we see on the browser side.

Most of the asynchronous objects in Node.js are inherited from the event.eventEmitter event object

Understand the mechanism of Node.js executing code

We can use Node Imagine the .js process as a restaurant:

The chef represents the JavaScript main thread. He is constantly busy executing the synchronization code on the main thread until it is completed.

//同步代码var a = 1;//同步代码var b = 2;//异步代码fs.readFile('./a.js',function(err,data){    if(err)throw data;
});//同步代码var c = 3;//异步代码setTimeout(function(){
},200);//同步代码console.log(a + b + c);//同步代码function fn(){    console.log('abc');
}//异步代码fs.writeFile('./b.js',myData,function(err){    if(err)throw err;
});
Copy after login

For example, the code like the one above is executed from top to bottom. When it encounters synchronous code, it is handed over directly to the chef to complete. However, when it encounters asynchronous code, it is not executed at this time, but It's like when a new customer arrives, he hands it to our waiter, and the waiter registers the dish ordered by the guest, which is equivalent to treating this asynchronous code as an event and recording it in our event queue.

When it's almost time, all the synchronization codes have been executed. At this time, the main thread will be idle. At this time, our event loop thread will be started. This event loop thread will start to check which guests have been registered by the waiter. After ordering the dishes, we will start frying their dishes one by one in order of priority, that is, executing our asynchronous codes, because there are many guests, and each guest's requirements are different, like Our Node.js code has various asynchronous codes, such as timers, file reading, file fetching, and network requests, so Node.js has a bunch of thread pools to handle these asynchronous codes.

When the asynchronous execution of a thread in the thread pool is completed, it is equivalent to the completion of the event, and the callback function corresponding to the event will be queued behind the main thread. .

Once there is new code to be executed on the main thread, the chef starts working as soon as he sees that there is something to do.

If the code corresponding to the callback function executed on the main thread generates new asynchronous code, it will be registered in the event loop.

Until a certain moment, all events in the event queue are executed, and the thread pool is slowly emptied.

node.js will call process.exit(), and the operating system will destroy the current node.js process.

It’s enough to understand the above, let’s go one step further:

When we get to the point of learning network programming, we know that when we know a server container, unless we take the initiative Use CTRL + C to terminate the current process, otherwise it will wait for the client connection and perform corresponding processing according to the corresponding route.

How to understand this?

Let’s recall the API we learned in jQuery. There are two ways to monitor events:

one one-time monitoring

on unlimited monitoring

We can Understand this way: Most file operations, ajax, etc., actually only need to be done once and it will end. There will not be a second time. They are equivalent to a one-type event model.

But if it involves network programming like socket, http, etc., it is equivalent to unlimited monitoring on.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

The concept of using independent scopes in angular

Detailed explanation of the use of $apply() in angularjs

The above is the detailed content of How Node.js code executes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template