A brief introduction to Node.js

Node.js Features

 

1. Single thread

 

In server-side languages ​​like Java, PHP, or .net, a new thread is created for each client connection. And each thread needs to consume about 2MB of memory. That is to say, in theory, the maximum number of users that can be connected to a server with 8GB of memory at the same time is about 4,000. To make a web application support more users, it is necessary to increase the number of servers, and of course the hardware cost of the web application goes up.

 

Instead of creating a new thread for each client connection, Node.js just uses one thread. When a user is connected, an internal event is triggered, and through the non-blocking I/O and event-driven mechanism, the Node.js program is macroscopically parallel. Using Node.js, an 8GB RAM server can handle over 40,000 simultaneous user connections.

 

In addition, with the benefit of single threading, the operating system no longer has the time overhead of thread creation and destruction.

The downside is that one user caused the thread to crash, the entire service crashed, and everyone else crashed.


technology sharing

technology sharing

 

2. Non-blocking I/O

 

For example, when accessing the database to get the data, it takes a while. In the traditional single-threaded processing mechanism, after executing the code to access the database, the entire thread will be suspended and wait for the database to return the result before executing the following code. That is to say, I/O blocks the execution of the code, which greatly reduces the execution efficiency of the program.

 

Since Node.js adopts a non-blocking I/O mechanism, after executing the code for accessing the database, the code behind it will be executed immediately, and the processing code of the result returned by the database will be placed in the callback function, thereby improving the program execution efficiency.

 

When a certain 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 that constantly checks for unhandled events and processes them in turn.

 

In blocking mode, a thread can only process one task, and multi-threading is necessary to improve throughput. In non-blocking mode, a thread is always performing computing operations, and the CPU core utilization of this thread is always 100%. So, this is a particularly philosophical solution: instead of having a lot of people, but a lot of people are idle, it is better to be alone and work to the death.

 

 

3. Event-driven event-driven

 

In Node, when the client requests to establish a connection, submit data and other behaviors, corresponding events will be triggered. In Node, at a time, only one event callback function can be executed, but in the middle of executing an event callback function, you can turn to process other events (for example, a new user is connected), and then return to continue executing the original event. The callback function, this processing mechanism, is called the "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 for the construction of event queues and callback function queues. Using event-driven to complete the task scheduling of the server, this is only a ghost can think of. The dance on the tip of the needle, with one thread, takes on the task of handling a very large number of tasks.

technology sharing

 

 

 

 

Single thread, the benefits of single thread, reduced memory overhead, memory paging of the operating system.

If something 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 statement.

Will non-blocking solve the problem? For example, in the execution of Xiaohong's business, Xiaogang's I/O callback is completed during the execution process. What should I do at this time? ?

The event mechanism and event loop, whether it is a new user's request or an old user's I/O completion, will be added to the event loop in an event mode, waiting for scheduling.

 

 

It is said that there are three characteristics, but in fact it is one characteristic.

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

All I/O in Node.js is asynchronous, callback functions, and sets of callback functions.

 

 

What is Node.js suitable for?

 

 

What kind of applications is Node.js suitable for?

 

Good at I/O, not good at computation. Because Node.js is best at task scheduling, if your business has a lot of CPU calculations, it is actually equivalent to this calculation blocking the single thread, which is not suitable for Node development.

 

Node.js is very suitable when the application needs to handle a lot of concurrent I/O without the need for very complex processing inside the application before the response is sent to the client. 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

● Live image and text

● Provide JSON API (used by front-end Angular)



 

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 a language and a platform", Node.js uses JavaScript for programming and runs on the JavaScript engine (V8).

 

● Compared with PHP, JSP, etc. (PHP, JSP, .net all need to run on server programs, Apache, Naginx, Tomcat, IIS), Node.js skips HTTP servers such as Apache, Naginx, IIS, etc. Build on top of any server software. Many of the design philosophies of Node.js are very different from the classic architecture (LAMP = Linux + Apache + MySQL + PHP) to provide great scalability. Node.js has no web container.



Example 1: The page displays "Hello World!"

 

JS code:

//require means to refer to the package, and the package is to refer to a special function of itself
var http = require(‘http‘);

//Create a server, the parameter is a callback function, indicating what to do if a request comes in
var server = http.createServer(function(req, res){
            //req means request, request; res means response, response

    //Set the HTTP header, the status code is 200, and the file type is html. Character encoding format is UTF-8
    res.writeHead(200, {‘Content-Type‘:‘text/html; charset= UTF-8; ‘});
    res.end(‘Hello World!‘);
});

//Run the server, listening on port 8083
server.listen(8083, ‘127.0.0.1‘);

 

Open the browser and enter 127.0.0.1:8083

technology sharing

 

Example 2: Node.js without a web container

When using the Apache server, we can often see that there are various subfolders in the htdocs directory. To access the specified page, we only need to enter 127.0.0.1:80/app/index.html in the browser address bar, something like this Structure

 

However, since Node.js does not have a web container, it does not display properly when entering /xx.xx after the url address

 

There is such a file directory structure:

technology sharing

 

Inside fang.html is a red, square div, and inside yuan.html is a green, round div

 

Now create a new noWebContainer.js and see if you can enter fang.html in the url to open the page

//require means to refer to the package, and the package is to refer to a special function of itself
var http = require(‘http‘);
var fs = require(‘fs‘);

//Create a server, the parameter is a callback function, indicating what to do if a request comes in
var server = http.createServer(function(req, res){
   
    res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});
    res.end("Hello World!");
    
});


//Run the server and listen on port 4000 (the port number can be changed arbitrarily)
server.listen(4000,"127.0.0.1");

 

Run 127.0.0.1:4000, and add /fang.html after the url, and find that it is completely useless

technology sharing

 

Now I have a little impression of the sentence "Node.js does not have a web container". What should I do if I want to open fang.html?

//require means to refer to the package, and the package is to refer to a special function of itself
var http = require(‘http‘);
var fs = require(‘fs‘);

//Create a server, the parameter is a callback function, indicating what to do if a request comes in
var server = http.createServer(function(req, res){
    if(req.url==‘/fang‘){
        fs.readFile(‘./fang.html‘, function(err,data){
            //req means request, request; res means response, response
            //Set the HTTP header, the status code is 200, the file type is html, and the character set is utf8
            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});
            res.end(data);
        })
    }else{
        res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});
        res.end("Hello World!");
    }
});


//Run the server and listen on port 4000 (the port number can be changed arbitrarily)
server.listen(4000,"127.0.0.1");

 

That is to say, if the requested url contains /fang, read fang.html in the current directory (./ ---> indicates the current directory), otherwise, only display Hello World

 

technology sharing

 

Similarly, I can also enter /yuan to display yuan.html

//require means to refer to the package, and the package is to refer to a special function of itself
var http = require(‘http‘);
var fs = require(‘fs‘);

//Create a server, the parameter is a callback function, indicating what to do if a request comes in
var server = http.createServer(function(req, res){
    if(req.url==‘/fang‘){
        fs.readFile(‘./fang.html‘, function(err,data){
            //req means request, request; res means response, response
            //Set the HTTP header, the status code is 200, the file type is html, and the character set is utf8
            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});
            res.end(data);
        })
    }else if(req.url==‘/yuan‘){
        fs.readFile(‘./yuan.html‘, function(err,data){

            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});
            res.end(data);
        })
    }else{
        res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});
        res.end("Hello World!");
    }
});


//Run the server and listen on port 4000 (the port number can be changed arbitrarily)
server.listen(4000,"127.0.0.1");

 

technology sharing

 

Further, add a picture in fang.html, as you can see from the above directory structure, the path of the picture is completely correct

<img src="yule.png" alt="图片">

 

Run 127.0.0.1:4000/fang, but found that the picture is broken, indicating that the path is wrong. But in fact, we can see that there is no problem with this path, so what should we do?

 

technology sharing

 

Back to the sentence, "Node.js does not have a web container", so, still use the previous method to process the picture

//require means to refer to the package, and the package is to refer to a special function of itself
var http = require(‘http‘);
var fs = require(‘fs‘);

//Create a server, the parameter is a callback function, indicating what to do if a request comes in
var server = http.createServer(function(req, res){
    if(req.url==‘/fang‘){
        fs.readFile(‘./fang.html‘, function(err,data){
            //req means request, request; res means response, response
            //Set the HTTP header, the status code is 200, the file type is html, and the character set is utf8
            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});
            res.end(data);
        })
    }else if(req.url==‘/yuan‘){
        fs.readFile(‘./yuan.html‘, function(err,data){

            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});
            res.end(data);
        })
    }else if(req.url==‘/yule.png‘){
        fs.readFile(‘./yule.png‘, function(err,data){

            res.writeHead(200, {"Content-type":"image/jpg"});
            res.end(data);
        })
    }else{
        res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});
        res.end("Hello World!");
    }
});


//Run the server and listen on port 4000 (the port number can be changed arbitrarily)
server.listen(4000,"127.0.0.1");

 

Run again, the picture can be displayed normally

technology sharing   technology sharing

 

 

Now create a yellow.css style sheet and let yuan.html import this css file

 

yellow.css

body{background:yellow;}

 

However, the background color of the page did not change in any way

technology sharing

 

It seems that the phrase "Node.js has no web container" is ubiquitous, and the css file needs to be processed as well.

//require means to refer to the package, and the package is to refer to a special function of itself
var http = require(‘http‘);
var fs = require(‘fs‘);

//Create a server, the parameter is a callback function, indicating what to do if a request comes in
var server = http.createServer(function(req, res){
    if(req.url==‘/fang‘){
        fs.readFile(‘./fang.html‘, function(err,data){
            //req means request, request; res means response, response
            //Set the HTTP header, the status code is 200, the file type is html, and the character set is utf8
            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});
            res.end(data);
        })
    }else if(req.url==‘/yuan‘){
        fs.readFile(‘./yuan.html‘, function(err,data){

            res.writeHead(200, {‘Content-type‘:‘text/html;charset=UTF-8‘});
            res.end(data);
        })
    }else if(req.url==‘/yule.png‘){
        fs.readFile(‘./yule.png‘, function(err,data){

            res.writeHead(200, {"Content-type":"image/jpg"});
            res.end(data);
        })
    }else if(req.url==‘/yellow‘){
        fs.readFile(‘./yellow.css‘, function(err,data){

            res.writeHead(200, {"Content-type":"text/css"});
            res.end(data);
        })
    }else{
        res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});
        res.end("Hello World!");
    }
});


//Run the server and listen on port 4000 (the port number can be changed arbitrarily)
server.listen(4000,"127.0.0.1");

 

Run the code again and find that the page background color has changed to yellow

technology sharing

 

 Original address: http://dapengtalk.blog.51cto.com/11549574/1886579

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325971858&siteId=291194637