Home > Web Front-end > JS Tutorial > body text

About the principle of nodejs as a server

零到壹度
Release: 2018-03-21 13:54:10
Original
2000 people have browsed it

This article mainly talks to you about the principle of nodejs as a server. Friends who need it can refer to it. I hope it can help everyone. Let’s take a look with the editor below.

Node.js Features

1. Single thread

In server-side languages ​​such as Java, PHP or .net, a new thread is created for each client connection. Each thread requires approximately 2MB of memory. In other words, theoretically, the maximum number of users that can be connected to a server with 8GB of memory at the same time is about 4,000. In order for a Web application to support more users, the number of servers needs to be increased, and the hardware cost of the Web application will of course increase.

#Node.js does not create a new thread for each client connection, but only uses one thread. When a user connects, an internal event is triggered. Through non-blocking I/O and event-driven mechanisms, the Node.js program is macroscopically parallel. Using Node.js, a server with 8GB of memory can handle the connections of more than 40,000 users at the same time.

#In addition, the benefits brought by single threading are that the operating system no longer has the time overhead of thread creation and destruction.

#The disadvantage is that if one user causes the thread to crash, the entire service will crash, and others will also crash.


About the principle of nodejs as a server

About the principle of nodejs as a server

##2. Non-blocking I/O

For example, when accessing the database to obtain data, it takes a while. In the traditional single-thread processing mechanism, after executing the code to access the database, the entire thread will pause and wait for the database to return the result before executing the subsequent code. In other words, I/O blocks the execution of the code, greatly reducing the execution efficiency of the program.

Since Node.js uses a non-blocking I/O mechanism, after the code that accesses the database is executed, the code behind it will be executed immediately. Put the processing code for the results returned by the database in the callback function, thereby improving the execution efficiency of the program.

When an I/O is completed, the thread performing the I/O operation will be notified in the form of an event, and the thread will execute the callback function of this event. In order to handle asynchronous I/O, the thread must have an event loop, constantly checking whether there are unhandled events, and processing them in turn.

In blocking mode, one thread can only handle one task. If you want to improve throughput, you must use multi-threading. In non-blocking mode, a thread is always performing calculation operations, and the CPU core utilization of this thread is always 100%. So, this is a particularly philosophical solution: Rather than having many people idle, it is better for one person to risk his life and work to death.

3. Event-driven event-driven

In Node, when the client requests to establish a connection, submit data, etc., corresponding events will be triggered. In Node, only one event callback function can be executed at a time, but in the middle of executing an event callback function, you can switch to processing other events (for example, a new user connects), and then return to continue executing the original event. Callback function, this processing mechanism is called "event loop" mechanism.

The bottom layer of Node.js is C++ (V8 is also written in C++). Nearly half of the underlying code is used to construct event queues and callback function queues. Using event-driven to complete server task scheduling is something only a genius can think of. The dance on the tip of the needle, with a thread, takes on the mission of handling a lot of tasks.

About the principle of nodejs as a server


It is said to be three characteristics, but in fact it is one characteristic. It can’t be used without anyone, and it can’t be played anymore.

Node.js is like a stingy restaurant owner who only hires one waiter to serve many people. As a result, it is more efficient than many waiters.

All I/O in Node.js is asynchronous, callback function, callback function.

What is Node.js suitable for development?

What kind of applications is Node.js suitable for developing?

Good at I/O, not good at calculation. Because Node.js is best at task scheduling, if your business involves a lot of CPU calculations, it actually means that this calculation blocks the single thread, and it is not suitable for Node development.

When the application needs to handle a large amount of concurrent I/O, and the application does not need to perform very complex processing before sending a response to the client, Node.js is a great fit. Node.js is also very suitable for working with web sockets to develop real-time interactive applications with long connections.

For example:

● User form collection

● Exam System

● Chat room

● Graphic and text live broadcast

● Provide JSON API ( For frontend Angular use)

The difference between Node.js and PHP and JSP

##● Node .js is not an independent language. Unlike PHP, JSP, Python, Perl, and Ruby, which are both languages ​​and platforms, Node.js uses JavaScript for programming and runs on a JavaScript engine ( V8).

● Compared with PHP, JSP, etc. (PHP, JSP, .net all need to run on the server program, Apache, Naginx, Tomcat, IIS), Node.js skips HTTP servers such as Apache, Naginx, IIS, etc. It does not need to be built on any server software. Many design concepts of Node.js are very different from the classic architecture (LAMP = Linux + Apache + MySQL + PHP), which can provide powerful scalability. Node.js does not have a web container.

Example 1: The page displays "Hello World!"

##JS code:

<span style="font-size: 14px;">//require表示引包,引包就是引用自己的一个特殊功能<br/>var http = require(‘http‘);<br/><br/>//创建服务器,参数就是一个回调函数,表示如果有请求进来,要做什么<br/>var server = http.createServer(function(req, res){<br/>            //req表示请求, request;res表示响应,response<br/><br/>    //设置HTTP头部,状态码是200, 文件类型是html。字符编码格式是 UTF-8<br/>    res.writeHead(200, {‘Content-Type‘:‘text/html; charset= UTF-8; ‘});<br/>    res.end(‘Hello World!‘);<br/>});<br/><br/>//运行服务器,监听8083端口<br/>server.listen(8083, ‘127.0.0.1‘);<br/></span>
Copy after login

Open the browser and enter 127.0.0.1:8083


About the principle of nodejs as a server

Example 2: Node.js has no web container

When using the Apache server, we can often Seeing that there are various subfolders in the htdocs directory, if we want to access the specified page, we only need to enter 127.0.0.1:80/app/index.html in the browser address bar, a structure similar to this

However, Node.js does not have a web container, so when /xx.xx is entered after the url address, it cannot be displayed normally

有这么一个文件目录结构:

About the principle of nodejs as a server

fang.html 里面是一个 红色的、正方形的p,yuan.html 里面是一个 绿色的、圆形的p

现在新建一个 noWebContainer.js,看能否在url中输入 fang.html 打开页面

<span style="font-size: 14px;">//require表示引包,引包就是引用自己的一个特殊功能<br/>var http = require(‘http‘);<br/>var fs = require(‘fs‘);<br/><br/>//创建服务器,参数是一个回调函数,表示如果有请求进来,要做什么<br/>var server = http.createServer(function(req, res){<br/>   <br/>    res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});<br/>    res.end("Hello World!");<br/>    <br/>});<br/><br/><br/>//运行服务器,监听4000端口(端口号可以任改)<br/>server.listen(4000,"127.0.0.1");<br/></span>
Copy after login

运行 127.0.0.1:4000,并在url后面加上 /fang.html,发现完全没用

About the principle of nodejs as a server

现在初步对“Node.js没有web容器”这句话有了一点印象了,那想要打开fang.html,怎么办呢?

<span style="font-size: 14px;">//require表示引包,引包就是引用自己的一个特殊功能<br/>var http = require(‘http‘);<br/>var fs = require(‘fs‘);<br/><br/>//创建服务器,参数是一个回调函数,表示如果有请求进来,要做什么<br/>var server = http.createServer(function(req, res){<br/>    if(req.url==‘/fang‘){<br/>        fs.readFile(‘./fang.html‘, function(err,data){<br/>            //req表示请求,request;  res表示响应,response<br/>            //设置HTTP头部,状态码是200,文件类型是html,字符集是utf8<br/>            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});<br/>            res.end(data);<br/>        })<br/>    }else{<br/>        res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});<br/>        res.end("Hello World!");<br/>    }<br/>});<br/><br/><br/>//运行服务器,监听4000端口(端口号可以任改)<br/>server.listen(4000,"127.0.0.1");<br/></span>
Copy after login

也就是说,如果 请求的url 里面包含了 /fang,就读取当前目录下(./ ---> 表示当前目录)的 fang.html,否则,就只显示 Hello World

About the principle of nodejs as a server

同理,我也可以 输入 /yuan,显示 yuan.html

<span style="font-size: 14px;">//require表示引包,引包就是引用自己的一个特殊功能<br/>var http = require(‘http‘);<br/>var fs = require(‘fs‘);<br/><br/>//创建服务器,参数是一个回调函数,表示如果有请求进来,要做什么<br/>var server = http.createServer(function(req, res){<br/>    if(req.url==‘/fang‘){<br/>        fs.readFile(‘./fang.html‘, function(err,data){<br/>            //req表示请求,request;  res表示响应,response<br/>            //设置HTTP头部,状态码是200,文件类型是html,字符集是utf8<br/>            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});<br/>            res.end(data);<br/>        })<br/>    }else if(req.url==‘/yuan‘){<br/>        fs.readFile(‘./yuan.html‘, function(err,data){<br/><br/>            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});<br/>            res.end(data);<br/>        })<br/>    }else{<br/>        res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});<br/>        res.end("Hello World!");<br/>    }<br/>});<br/><br/><br/>//运行服务器,监听4000端口(端口号可以任改)<br/>server.listen(4000,"127.0.0.1");<br/></span>
Copy after login


About the principle of nodejs as a server

进一步,在 fang.html 中添加一个图片,从上面的目录结构中可以看到,图片的路径是完全正确的

<span style="font-size: 14px;"><img src="yule.png" alt="图片"><br/></span>
Copy after login

运行 127.0.0.1:4000/fang,却发现图片破了,说明路径不对。但事实上,我们可以看到,这个路径是一点问题都没有的呀,那怎么办呢?

About the principle of nodejs as a server

又回到了那句话,Node.js没有web容器”,所以,还是要用前面的方法处理一下图片

<span style="font-size: 14px;">//require表示引包,引包就是引用自己的一个特殊功能<br/>var http = require(‘http‘);<br/>var fs = require(‘fs‘);<br/><br/>//创建服务器,参数是一个回调函数,表示如果有请求进来,要做什么<br/>var server = http.createServer(function(req, res){<br/>    if(req.url==‘/fang‘){<br/>        fs.readFile(‘./fang.html‘, function(err,data){<br/>            //req表示请求,request;  res表示响应,response<br/>            //设置HTTP头部,状态码是200,文件类型是html,字符集是utf8<br/>            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});<br/>            res.end(data);<br/>        })<br/>    }else if(req.url==‘/yuan‘){<br/>        fs.readFile(‘./yuan.html‘, function(err,data){<br/><br/>            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});<br/>            res.end(data);<br/>        })<br/>    }else if(req.url==‘/yule.png‘){<br/>        fs.readFile(‘./yule.png‘, function(err,data){<br/><br/>            res.writeHead(200, {"Content-type":"image/jpg"});<br/>            res.end(data);<br/>        })<br/>    }else{<br/>        res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});<br/>        res.end("Hello World!");<br/>    }<br/>});<br/><br/><br/>//运行服务器,监听4000端口(端口号可以任改)<br/>server.listen(4000,"127.0.0.1");<br/></span>
Copy after login

再次运行,图片可正常显示

About the principle of nodejs as a server About the principle of nodejs as a server

现在新建一个 yellow.css 样式表,让 yuan.html 引入这个css 文件

yellow.css

<span style="font-size: 14px;">body{background:yellow;}<br/></span>
Copy after login

但是,页面的背景颜色没有发生任何改变

About the principle of nodejs as a server


看来 “Node.js没有web容器”这句话是无处不在呀,同样需要对 css 文件做处理

<span style="font-size: 14px;">//require表示引包,引包就是引用自己的一个特殊功能<br/>var http = require(‘http‘);<br/>var fs = require(‘fs‘);<br/><br/>//创建服务器,参数是一个回调函数,表示如果有请求进来,要做什么<br/>var server = http.createServer(function(req, res){<br/>    if(req.url==‘/fang‘){<br/>        fs.readFile(‘./fang.html‘, function(err,data){<br/>            //req表示请求,request;  res表示响应,response<br/>            //设置HTTP头部,状态码是200,文件类型是html,字符集是utf8<br/>            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});<br/>            res.end(data);<br/>        })<br/>    }else if(req.url==‘/yuan‘){<br/>        fs.readFile(‘./yuan.html‘, function(err,data){<br/><br/>            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});<br/>            res.end(data);<br/>        })<br/>    }else if(req.url==‘/yule.png‘){<br/>        fs.readFile(‘./yule.png‘, function(err,data){<br/><br/>            res.writeHead(200, {"Content-type":"image/jpg"});<br/>            res.end(data);<br/>        })<br/>    }else if(req.url==‘/yellow‘){<br/>        fs.readFile(‘./yellow.css‘, function(err,data){<br/><br/>            res.writeHead(200, {"Content-type":"text/css"});<br/>            res.end(data);<br/>        })<br/>    }else{<br/>        res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});<br/>        res.end("Hello World!");<br/>    }<br/>});<br/><br/><br/>//运行服务器,监听4000端口(端口号可以任改)<br/>server.listen(4000,"127.0.0.1");<br/></span>
Copy after login

再次运行代码,发现页面背景颜色变成了黄色

About the principle of nodejs as a server

##Single thread, The benefits of single threading are that it reduces memory overhead and memory paging of the operating system.

If a certain thing enters but is blocked by I/O, the thread is blocked.

Non-blocking I/O, will not wait for the I/O statement to end, but will execute the following statements.

Can non-blocking solve the problem? For example, while executing Xiaohong's business, Xiaogang's I/O callback is completed. What should I do at this time? ?

Event mechanism, event loop, Whether it is a new user's request or an old user's I/O completion, the event will be added in the event mode Ring, waiting for dispatch.

The above is the detailed content of About the principle of nodejs as a server. 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