Home > Article > Web Front-end > Node.js tutorial for beginners (1)
This time I will bring you a novice tutorial on Node.js. What are the precautions for using Node.js tutorial? Here are practical cases, let’s take a look.
Main line: What is Node.js--> The composition of Node.js--> Characteristics of Node.js--> Helloworld example--> Module--> Core module-- > Local module--> Package--> Package manager--> Non-blocking, single-threaded, event-driven--> Callback function--> Node application
What is Node? First look at its name, Node.js. At first glance, some people think that this thing may be a library or framework like jQuery, but in fact it is not. Node.js is a platform that allows JavaScript to run on the server. , or Node.js is a tool that allows JavaScript to run in a non-browser environment. Node.js uses what is known as the fastest chrome v8 engine in the world. It is composed of two parts, including Core JavaScript and Node Composed of the Standard Library, Core JavaScript actually refers to ECMAScript, which means it only includes the ECMAScript in our js scripts on the browser side, excluding our document object model, which is DOM, and the browser object model. That is BOM. Some people think that Node has compatibility issues? There is no compatibility problem with Node, because we have studied the js script of the client browser and we should understand that the js compatibility problem we often talk about actually refers to the compatibility problem of our DOM and BOM, so what is Node Standard Library, this is similar to our C standard library or C++ standard extension library. The characteristic of Node.js is non-blocking asynchronous event-driven. Node.js allows our JavaScript to be embedded in our scripting world. First-class citizens, let's first look at the first example, helloworld. This helloworld seems to be more complicated than other languages? But we can take a look at the functions implemented by these 6 lines of code. It implements a simple server. One of the pillars of Node.js is the module, so the first thing we need to learn is the module. So what is a module? A module is actually a js file. In our client browser, if we want to embed a css file and introduce another css file, we can use the @import directive, but in our js, if we want to introduce another css file js, it is not that easy. Of course, it does not mean that it cannot be achieved. We can create a script tag through createElement, and then appendChild to our html to achieve it. But no matter what, it is not that easy to implement. Yes, our Node has solved this problem. In our Node, a js file is directly a module. We have created two js files, so how can we introduce another js file into one js file? We can introduce it through a function called require. We can treat each module as a larger object. They will eventually expose some properties and methods. We do it through a function called exports, or module.exports. Modules that expose attributes and methods are divided into two types. One is the core module. Common core modules include the http module, the os module, which is an operating system-related module, and the fs module, which is a file system module that processes and files operations. things, util module tools, and the other is the local module. The so-called local module means that we can create our own module by ourselves. Compared with the module, a larger unit is the package. What is a package? We can think about it, we can think of a module as one of our files, and we can think of the package as a folder, which means we can use a folder to put a bunch of files with similar functions together and package them. When it comes to packages, in addition to the packages we create ourselves, the more important thing is actually some third-party packages. On the npm.org website, there are a large number of third-party packages that have been implemented by tens of thousands of people. We want to use it, how to use it specifically?In order to make it easier for us to use third-party packages, our Node has developed a tool called the package management tool, which is our npm. We can simply take a look at how to use this thing. We have two ways to install it. One One is global installation, and the other is local installation. This may not be exactly the same as other languages. For example, like python and ruby, globally installed packages are generally suitable for command line operations. For example, like our lessc, another local package is generally It is used in some projects we are currently working on. Of course, if it only has these things, then Node.js has no big features, because these things are actually already available in other languages such as python and ruby. Well, the biggest feature of Node.js is actually the asynchronous non-blocking and event programming modules. This should be a completely subversive design, which is very different from other languages. For example, the following are two examples. I hope everyone can understand this example. , assuming that what we implement is synchronous IO, and what we want to query is a SQL statement. Usually we will write the following code, such as python, such as php, which are all in this form, that is, first use db.query and then a SQL queries will block and wait for the database to return the results and store them in a res variable, but the following is the real way of writing Node. This uses asynchronous IO. It can be seen that in fact, this statement, In fact, this is a statement. It generates such a SQL query and puts a function in the second parameter. This function is called a callback function, which means that after the statement is executed, it will not be executed directly. res.auto, it will continue to execute backwards. When will the content inside be executed? Wait until my database returns the message, then enter the callback function through the event loop, and then print out the query results. This is the asynchronous IO mode. Then I will explain what is synchronization and what is asynchronous, and the program is executing IO The operation may take a long time, which may last hundreds of thousands or hundreds of millions of instruction cycles, but it may only take you a few hundred or thousands of instruction cycles to execute a JavaScript statement. Of course, it may be optimized. It may only take a few dozen, so it is a waste of time after encountering IO. The operating system and CPU implement asynchronous scheduling methods through interrupts, which means that when the process initiates an IO request, the operating system will hang. The current process will then give up control of the CPU to other processes. When the IO is completed, the operating system will resume the original process and continue execution. At the same time, you can access the results of the IO operation just now. This request method is called It is synchronous IO, or blocking IO, but in the IO mode in Node, we use asynchronous IO, or non-blocking IO. This means that when the process initiates an IO request, it immediately returns and continues to perform other tasks. instruction, and then use other means to notify that the IO operation has been completed, and then process the logic code after the IO operation is completed. Then when non-blocking IO is initiated, the process will not enter the blocking state, but will continue to execute the event. Other parts, and then enter the event loop to handle other events. The concept of an event and event loop is mentioned here. All calculation logic operations in Node will be abstracted into an event, and then the entire program is an event loop, and the event loop will continue Processing something called an event queue, that is to say, I have an event at the beginning, and then some requests may be initiated during the execution process, such as IO requests. After the IO request is completed, the event queue will be added to the event queue. Wait for the process to enter the event loop before processing. This is a processing mode based on the event loop. This event-driven mode is actually a very classic and commonly used mode, such as qt, gtk. For example, a mouse click is an event. For example, timer is also an event, and an event requires a callback function. The so-called callback function refers to when our event occurs. Then why does Node use this obscure programming model?In fact, this is another very special strategy of Node. It uses single-threaded mode. Let's first talk about the concurrency model of blocking mode. For example, if we want to develop a web server, of course it must have concurrency requirements. It can allow multiple Users access at the same time. It does not mean that I have processed one user's request and then processed the second user's request. In this case, when there are more users, the processing speed will be very slow. When one user is very slow and does not disconnect, , other users will keep waiting, which is unreasonable. To achieve concurrency in blocking mode, multi-threading must be used, that is, one process can only handle one task. If we want to improve the throughput of the CPU, What must be used is multi-threading, which may be much more than the number of CPU cores. How many more threads are needed? This is unpredictable. For example, for one of our logic, he needs to calculate a part first and then initiate a IO requests, such as reading a file or writing a file, or initiating a network request, then enter our second calculation part. To achieve concurrency, we can use multi-threading mode, and its execution may be One such example, assuming we have a single CPU, then first the first thread seizes the CPU for calculation, and then it reaches the IO request stage and becomes blocked. At this time, the control of the CPU will be transferred, and then at this time The second thread will seize the CPU, then enter IO, be blocked again, and then release control of the CPU, thread 3, thread 4, thread 5, etc., and then there may be a period of idle time in the middle, and then wait for thread 1 The IO is over, and then it finds that the CPU is not occupied, it will use the CPU to enter calculations, such a concurrent preemptive mode based on calculation and IO, but under the non-blocking model, its model will be like this, a Single-threaded, Calculation 1 will initiate an asynchronous IO request. At this time, it will directly enter another Calculation 1, which may be Calculation 1 initiated by another user, and then initiate a second request, and then wait for 5 users. After the initiation, the calculation of the first user has ended at this time, and then our event loop is a single thread that will execute the IO request initiated by the first user. In theory, the utilization of the CPU by the process in non-blocking mode It is 100%. This is an ideal situation. A single thread can achieve the maximum throughput, and multiple threads are not needed. Then when do you need multiple threads? When we have multiple cores, for example, if we have 2 cores, we will open 2 threads. Then, what is the advantage of non-blocking over blocking? Multi-threading sounds fast, but in fact it is not that fast. Because of the switching, the time slice segmentation will be very small. Switching stations every 20ms is very inefficient in the utilization of CPU cache, and non-blocking is not very good either. Yes, it will easily cause callback hell. Read the first file first, and then read the second file. This is a mongoDB operation. I’ve just introduced the basics of Node here. After talking about Node for a long time, what are the applications of Node? First of all, Node has many third-party modules. For example, if we want to make a web website, we can use the express framework. Then we can use a template engine called jade to generate html. There are less and stylus to generate css, and there are javascript compression tools. uglify, using websocket has socket.io, SQL database has ORM, oAuth, daemon process, command line parsing, syntax analysis, including Node.js. Although it has nothing to do with DOM, it can actually process, file upload, syntax Highlighting, parsing markdown, encoding conversion image processing, lightweight threads and coroutines, coffeescript, and some static analysis on the browser side. Thank you all. This is my introduction to Node.js today.
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 execution principle of Node.js code
Detailed explanation of the use of $apply() in angularjs
The above is the detailed content of Node.js tutorial for beginners (1). For more information, please follow other related articles on the PHP Chinese website!