search
HomeWeb Front-endJS TutorialAbout the principle of nodejs as a server

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>

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>

运行 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>

也就是说,如果 请求的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>


About the principle of nodejs as a server

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

<span style="font-size: 14px;"><img src="/static/imghwm/default1.png"  data-src="yule.png"  class="lazy"   alt="图片"><br/></span>

运行 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>

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

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>

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

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>

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

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!

Statement
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
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

火了!新的JavaScript运行时:Bun,性能完爆Node火了!新的JavaScript运行时:Bun,性能完爆NodeJul 15, 2022 pm 02:03 PM

今天跟大家介绍一个最新开源的 javaScript 运行时:Bun.js。比 Node.js 快三倍,新 JavaScript 运行时 Bun 火了!

nodejs中lts是什么意思nodejs中lts是什么意思Jun 29, 2022 pm 03:30 PM

在nodejs中,lts是长期支持的意思,是“Long Time Support”的缩写;Node有奇数版本和偶数版本两条发布流程线,当一个奇数版本发布后,最近的一个偶数版本会立即进入LTS维护计划,一直持续18个月,在之后会有12个月的延长维护期,lts期间可以支持“bug fix”变更。

聊聊Node.js中的多进程和多线程聊聊Node.js中的多进程和多线程Jul 25, 2022 pm 07:45 PM

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

深入浅析Nodejs中的net模块深入浅析Nodejs中的net模块Apr 11, 2022 pm 08:40 PM

本篇文章带大家带大家了解一下Nodejs中的net模块,希望对大家有所帮助!

怎么获取Node性能监控指标?获取方法分享怎么获取Node性能监控指标?获取方法分享Apr 19, 2022 pm 09:25 PM

怎么获取Node性能监控指标?本篇文章来和大家聊聊Node性能监控指标获取方法,希望对大家有所帮助!

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools