Home Web Front-end JS Tutorial Node.js tutorial for beginners (1)

Node.js tutorial for beginners (1)

Mar 12, 2018 pm 05:17 PM
javascript node.js newbie

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for playing the Mist Lock Kingdom to give newbies a guide Tips for playing the Mist Lock Kingdom to give newbies a guide Jan 28, 2024 pm 03:33 PM

Mistlock Kingdom is an open world game where players can play as Sons of Fire to survive and explore. The game combines the unique entertainment of action RPG challenges, bringing players endless surprises and joy. In the game, players can explore resources, environments, weapons and more. Some novice players may be curious about how to get started with the game. In this introduction and sharing, we will provide you with some relevant getting started guides. Tips for Beginners to the Fog Lock Kingdom: The danger levels of areas shrouded by miasma are different. During the exploration process, new areas of the map will be gradually unlocked, and the location of the areas shrouded by miasma can be seen. The map will be distinguished by two colors. The blue area can be entered in a short time. The time you can stay will also be different depending on the character's ability level.

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Anchor Point Advent Novice Ten Company Character Recommendations Anchor Point Advent Novice Ten Company Character Recommendations Feb 20, 2024 pm 02:30 PM

Anchor Arrival is a 3D turn-based card game with a high-definition beautiful girl two-dimensional theme. It provides a rich and exciting combination of characters for players to explore and experience. It has many powerful combinations of high-quality lineups. New players are also curious novices. What powerful characters are recommended in the pool? Let’s take a look at the selection reference for novices to win ten consecutive golds! Anchor Point Advent is a powerful character recommendation for novice pools. The first ten-consecutive pick is Alice. She is mainly a single-target lightning-type burst character. The output is very explosive, and the experience will be very friendly to newcomers, so it is highly recommended to choose it. It is recommended to choose the combination of "Alice" + "Antelope" for 10 points. Alice is the most worthy character to output the goldpire attribute, and is not even a bit stronger than the other two characters in the novice card pool. Alice can pass special

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Learning to use batch indentation is a skill that PyCharm newbies must master Learning to use batch indentation is a skill that PyCharm newbies must master Dec 30, 2023 pm 12:58 PM

Essential skills for newbies to PyCharm: Mastering the use of batch indentation requires specific code examples Overview: PyCharm is a powerful Python integrated development environment (IDE) that provides many practical tools and functions to help developers improve efficiency . In the daily coding process, we often need to indent the code to keep the code format neat and beautiful. The batch indentation function provided by PyCharm can help us quickly batch indent the code and improve coding efficiency. This article will explore Py

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Ancient Crown Beginner's Guide and Gameplay Introduction Ancient Crown Beginner's Guide and Gameplay Introduction Feb 20, 2024 am 11:20 AM

Crown of the Ancients is a high-quality and strategic card mobile game based on Western magical adventure. In-game secret exploration, ruins adventure, national championship and other special gameplay are waiting for you to experience. So for novice players, if they want to get started with this game quickly, a novice guide is indispensable. Today, the editor will bring you the relevant guide, let’s take a look. An overview of the Ancient Crown beginner’s guide, gameplay and area opening styles: 1. Diamond accumulation flow: Everything is focused on accumulating diamonds, and then you start to work hard after leaving the village. Except for the main magic weapon, three flywheel activities, etc., which require diamonds, the others are ignored. The main focus is on one of them. Don't pay attention to the hero challenge. You can fight as many as you can, and don't force it. Advantages: You only need to mess around to accumulate diamonds. After leaving the village, you can quickly access the latest activities with diamonds, get new series of hardware heroes, and diamonds are broken.

See all articles