Cultivation of ability must continue to do, and must always improve learning methods, improve learning efficiency, will be successful. – ye shengtao

Why do we use Node and what are its benefits?

The primary goal of Node is to provide a simple development tool for creating high-performance servers. You also have to deal with highly concurrent user requests from the Web server.

Solve high concurrency?

Let’s take an example of which node is better than Java for the same request. Look at the picture

  • Node can handle user requests better than JavaconcurrentPerformance, which can quickly bind events through the main thread. Java creates one thread at a time, although Java now has oneThe thread poolThe concept can control the reuse and number of threads.
  • With asynchronous I/O operations, Node can operate databases faster. Java encounters a parallelism problem when accessing a database, requiring the addition of a concept of locks. For example, when you go to the water dispenser to get water after class, Java means that many people go to get water at a time and need to wait, while Node means that only one person goes to get water at a time.
  • CPU intensive operations are logical processing operations, compression, decompression, encryption, and decryption. Node blocks the main thread for CPU intensive operations(Single thread), resulting in the time below it cannot be quickly bound, soNode is not suitable for large, intensive CPU operationsJava fits the bill.

Node on the Web?

The Web-side scenario, where the user requests or reads static resources, is ideal for Node development. Application scenarios mainly include chat servers, e-commerce websites and other highly concurrent applications.

What is node?

Node.js is a JavaScript based on the Chrome V8 engineOperating Environment (Runtime)Node is not a language. It has JS running on the back endThe runtime, and does not include the full javascript set, because it is not included on the server sideDOMandBOMNode also provides some new modules for examplehttp,fsModule, etc. Node. Js for useEvent-driven, non-blocking I/ONode.js package manager, making it lightweight and efficientnpm, is the world’s largest open source library ecosystem.

In short, in short, it’s just a runtime, a runtime environment.

The node properties

  • The main thread is single-threaded (asynchronous), passing the subsequent logic as a function to the currently executed function, and executing the function when the result of the executed function is obtained(Callback function).
  • Five people eat a bowl of rice at once (asynchronously).
  • Blocking cannot be asynchronous (now assume that the database is the cook, the server is node, and the customer is the request. Generally, the cook cooks the food and asks the server to pass it to multiple users. If the cook invites the server to chat, it will cause blocking, and it is said to the kernel).
  • I/O operation, read/write operation, asynchronous read/write (asynchronous but not synchronous)Non-blocking I/O, that is, asynchronous read and write.
  • event-drivenevent-drivenPublish and subscribe.

Node processes and threads

Process is the basic unit of the operating system to allocate resources and schedule tasks. Thread is a program running unit built on the process. There can be multiple threads on a process.

Before we do that, let’s look at the process mechanism of the browser

From top to bottom, they are:

  • User interface – address bar, bookmark menu, etc
  • Browser engine – Transfer instructions between the user interface and the rendering engine (the main process of the browser)
  • Rendering engine – browser kernel such as (WebKit, Gecko)
  • Others – Network requests, JS threads and UI threads

From our point of view, we’re more concerned with the browser’s rendering engine, so let’s move on.

Rendering engine

  • The rendering engine ismultithreadingContains the UI thread and JS thread. The UI thread and the JS thread doThe mutex, because the running results of the JS thread will affect the UI thread, UI updates will be stored in the queue until the JS thread is idle, then it will be taken out for update.
  • Js single thread is single thread, why? DOM if js is multithreaded, so operation is a multi-threaded operation, it will be very confusion, DOM’t know who should listen to, and in this case, the single thread is the main thread is single-threaded, he also can have asynchronous thread, through the queue to store these threads, and the main thread is still single thread, which we speak again later. So js is also single threaded in Node.
  • The advantage of single threading is that it saves memory, doesn’t need to execute context when switching, and doesn’t have to worry about the concept of locking because we’re passing one at a time.

3. Event Loop in browser

Here I will first talk about the browser event ring, some people may say, your article is clearly about Node how can talk about the browser. First of all, they are different runtime with JS as the underlying language, which has its similarities. Moreover, they are not afraid of being asked more by the interviewer. Okay, without further ado, here we go.

First we need to understand the relationship and meaning of heap, stack and queue.

  • Heap: A space where objects (objects, functions) are stored
  • Queue (loop) : Stores the results of all asynchronous request operations until an asynchronous operation completes its mission, and an event is added to the loop.The queue is first in, first outFor example, in the picture below, the most advanced queue will be kicked out first

  • Stack (stack) : the stack itself is the storage of basic variables, such as 1,2,3, as well as reference variables. And I’m going to explain it a little bit here, because it’s in the stackReference variablesIt refers to the reference object in the heapaddress.It’s just a bunch of addresses. Here stack represents the execution stack, the main thread of our JS.Stacks are first in, last out, advanced after out is equivalent to drinking water cup, we pour water into, theoretically drink the water is the last into the cup. We can look at the code,follow me.
function a(){
  console.log('a')
  function b(){
    console.log('b')    
    function c(){
      console.log('c')
    }
    c()
  }
  b()
}
a()

// This code outputs a,b,c, executing the order OF C,b, A in the stack, or c, b, A if it follows first-in, first-out. So this is a very important thing to keep in mind.
Copy the code

OK, now that you know the relationship between heap, stack and queue, let’s look at a picture.

Let me analyze this graph

  • Our synchronization tasks running on the main thread form an execution stack
  • If you have an asynchronous task, for exampleSetTimeout, onClickAnd so on, and we’re going to queue its execution, and the main thread is not blocking
  • When all synchronization tasks in the main thread are completed, it will passevent loopFetch from scratch in the queue and execute on the stack
  • event loopNever cut off
  • This whole process isEvent Loop(Event loop mechanism)

Micro task, macro task?

Macrotask: setTimeout, setImmediate, MessageChannel Native Promises (some implemented promises put then methods in macro tasks), Object.Observe (deprecated), MutationObserver

Both micro tasks and macro tasks are asynchronous tasks, which belong to the same queue. The main differences lie in their execution sequence and the direction and value of Event Loop. So what’s the difference between them

Each time the synchronization task on the execution stack is completed, it will fetch the completed asynchronous task from the task queue, and the queue is divided into two partsMicrotask queues and macro task queuesWait until theQueues All microtasksAll done. Be advisedAll of the“, he will fromMacro task queueMiddle take event. Wait until you get the event out of the queueaPut it on the stack and execute it, even if the loop ends once, and thenevent loopIt’s going to continue. He’s going to go againmicrotasks queuesPerform all the tasks, and then fromMacro task queueIt takeaAnd so on.

  • The synchronization task is complete
  • To carry outmicrotasksAnd all themicrotasks queuesempty
  • Take out amacrotasks queuesThe completion event is executed in the execution stack
  • To performmicrotasks
  • .
  • .
  • .

I’m going to confuse you a little bit by saying this, but let’s do one

setTimeout((a)= >{
  console.log('setTimeout1')},0)
let p = new Promise((resolve,reject) = >{
  console.log('Promise1')
  resolve()
})
p.then((a)= >{
  console.log('Promise2')})Copy the code

The final output is Promise1, Promise2, setTimeout1

  • Promise1 in the Promise parameter is executed synchronously, Promise is not very well understood if you look at my other article Promise, Promise, Promise,
  • Second, because Promise ismicrotasksWill go after the synchronization task is completedemptymicrotasks queues.
  • Finally empty the micro task to go to the macro task queue value.
Promise.resolve().then((a)= >{
  console.log('Promise1')  
  setTimeout((a)= >{
    console.log('setTimeout2')},0)
})

setTimeout((a)= >{
  console.log('setTimeout1')
  Promise.resolve().then((a)= >{
    console.log('Promise2')})},0)
Copy the code

This is nested, and if you look at it, it’s going to output Promise1, setTimeout1, Promise2, setTimeout2

  • Once the stack synchronization task is executed, it will gomicrotasks queuesLooking for a
  • emptymicrotasks queuesAnd the outputPromise1, and an asynchronous task setTimeout1 is generated
  • Go to theMacro task queueThe queue is setTimeout1 before setTimeout2, because the setTimeout1 stack starts asynchronously, so the outputsetTimeout1A microtask of the Promise2 that is generated when setTimeout1 is executedmicrotasks queuesIn the
  • And then another cycle, to empty itmicrotasks queuesAnd the outputPromise2
  • Empty outmicrotasks queues, will go to the macro task queue again, this time fetch issetTimeout2

Event rings in node

Node’s event ring is not the same as the browser’s. Let’s take a look at its workflow

  • First we can see our JS code(APPLICATION)I’m going to go to the V8 engine first, and the V8 engine is mainly somesetTimeoutAnd so on.
  • Second, if we implement nodeApi in our code, for examplerequire('fs').read(), node will be handedlibuvLibrary processing, this onelibuvThe library is written by someone else, who is node’s event loop.
  • libuvThe library handles events in a single-threaded, asynchronous manner, as we can seework threadsIt’s a multithreaded queue that goes through the outsideevent loopBlock to make asynchronous calls.
  • Wait until thework threadsIf there is an event in the queue that has completed execution, it will passEXECUTE CALLBACKThe callback toEVENT QUEUEQueue, put it in the queue.
  • Finally, the event-driven method is used to extractEVENT QUEUEQueue events to our application

Event loop in node

The event loop in node is in libuv. Libuv has an event loop mechanism, which initializes the event loop when starting node

  • Each of these phases corresponds to an event queue
  • Every timeevent loopWhen the execution reaches a certain stage, the correspondingThe event queueAre executed in sequence
  • When the queue is complete or the number of executions exceeds the upper limit,event loopThe next stage is executed
  • Every timeevent loopWhen an execution queue is switched, it is emptiedmicrotasks queues, then switch to the next queue to execute, and so on

We have to be careful heresetImmediatePoll queues are mainly asynchronous I/O operations, such as fs.readfile () in Node.

Let’s see how he uses it

setImmediate((a)= >{
  console.log('setImmediate1')
  setTimeout((a)= >{
    console.log('setTimeout1')},0)
})
setTimeout((a)= >{
  console.log('setTimeout2') 
  process.nextTick((a)= >{console.log('nextTick1')})
  setImmediate((a)= >{
    console.log('setImmediate2')})},0)
Copy the code
  • First we can see that the above code executes firstsetImmediate1At this time,event loopinCheck the queue
  • thensetImmediate1After fetching from the queue, outputsetImmediate1And then it willsetTimeout1perform
  • At this timeevent loopafterCheck the queueAnd then I’m going to move down, and then I’m going to doTimers queue
  • There will be problems here, we all know thatsetTimeout1If you set the delay to 0, it’s still there4msSo there are two things going on here. Let’s start with the first onesetTimeout1Execution completed
    • According to the rules of the Node event loop, we will execute all events, i.e., fetchTimers queueIn thesetTimeout2,setTimeout1
    • In this case, the output sequence is based on the fifO rulesetTimeout2,setTimeout1In the outsetTimeout2When, will be aprocess.nextTickExecute (execute is put inMicrotask queue), and one moresetImmediateExecute (execute is put inCheck the queue)
    • At this point,event loopIt’s going to look for the next event queueevent loopWill findMicrotask queueThere are eventsprocess.nextTickI’m going to empty it, outputnextTick1
    • The lastevent loopFind the next queue with an eventCheck the queue, the implementation ofsetImmediateAnd the outputsetImmediate2
  • If heresetTimeout1Has not completed the execution (4MS delay its lifetime event?)
    • At this timeevent loopfindTimers queueTo retrieve the timers queue **setTimeout2And the outputsetTimeout2,process.nextTickExecute, and thensetImmediateperform
    • thenevent loopI need to find the next event queue,I want you to pay attention here, 2 steps will take place,1.setTimeout1After executing the timers command, the timers are placed in the timers queue. 2. Find the microtask queue empty., so it prints firstnextTick1
    • The followingevent loopWill findCheck the queueAnd take out the ones that have been executedsetImmediate2
    • The lastevent loopfindTimers queue, take out the executedsetTimeout1.In this caseevent loopIt takes one more toggle than above

So there are two answers

  1. setImmediate1,setTimeout2,setTimeout1,nextTick1,setImmediate2
  2. setImmediate1,setTimeout2,nextTick1,setImmediate2,setTimeout1

The diagram here only refers to the first case, and the other case is similar

5. Node synchronization, asynchrony, blocking and non-blocking

  • Synchronization: the process of waiting for the caller. If the caller never returns the result, the caller will always wait. This is synchronization, and synchronization has a return value
  • Asynchronous: That is, the caller does not wait for the call to return. The caller will send status, notification, or callback functions to the caller when the call is finished. Asynchronous has no return value
  • Block: Indicates that the current thread is suspended until the result is returned
  • Non-blocking: that the current thread continues to execute no matter what you return

Some people may mess with their relationships,Synchronous and asynchronousIs the state of the called,Blocking, non-blockingIs the caller’s status, message

Now let’s see what the combination would look like

combination meaning
A synchronized block It’s like when I go to a restaurant and I have to wait in the kitchen for the food to be ready before I can eat it. I’m the caller and I need to wait for the dish to be served so it’s blocked, and the dish is served to me directly by the caller which is synchronous
Asynchronous blocking I went to a restaurant for dinner, and I needed to wait for the dishes to be ready before I could eat them, but the chef had something to do, and he hoped that he would inform me to take them after the processing was finished. As the caller, I would be blocked waiting, while as the called, the dishes would be notified to me after they were finished, so it was asynchronous and generally useless.
Synchronous nonblocking I go to a restaurant to have a meal, first ordered a bowl of hot dishes, in the kitchen, waiting for the chef to cook, but I am very hungry, began to eat the kitchen cold dishes, I am the caller, I did not wait for the hot dishes ready to eat cold dishes, non-blocking, dishes as the call done directly to me is synchronous, this way is generally no one use
Asynchronous nonblocking I went to a restaurant for dinner. I ordered a bowl of hot dishes, the cook was cooking, but I was very hungry, eat the cold dishes first, the cook cooked the notification to me to take, I am the caller, I will not wait for the hot dishes cooked before eating cold dishes, non-blocking, dishes as the called notice I take is asynchronous

At the end

I hope you all learned something from this article, so you don’t have to go out and interview like this

Meet bet will win
In the final