1 Let’s start with the name

There are more and more technical reports about Node.js, and there are many different ways to write node.js. There are many different ways to write node.js. On the official Node.js website, the project has been referred to as “Node” or “Node.js,” but no other references have been found,” The word “Node” is most commonly used. Considering that the meaning and use of the word “Node” is too broad, which is easy to be misunderstood by developers, we adopt the second name — “node.js”. The suffix of JS points to the original meaning of Node project, and other names are various without exact origin, so we do not recommend using them.

What problem is 2 Node designed to solve

Node’s stated goal is “to provide an easy way to build scalable network applications.” What’s wrong with the current server program? Let’s do a math problem. In languages such as Java™ and PHP, each connection generates a new thread, and each new thread may require 2 MB of accompanying memory. On a system with 8 GB of RAM, the theoretical maximum number of concurrent connections is 4,000 users. As your customer base grows, you must add more servers if you want your Web application to support more users. Of course, this increases server costs, traffic costs, labor costs, etc. In addition to these cost increases, there is a potential technical problem that users may use different servers for each request, so any shared resources must be shared across all servers. For all of the above reasons, the bottleneck in the overall Web application architecture (traffic, processor speed, and memory speed) is the maximum number of concurrent connections the server can handle.

Node solves this problem by changing how it connects to the server. Instead of generating a new OS thread for each connection (and allocating some associated memory), each connection emits an event that runs in the Node engine’s process. Node claims that it never deadlocks, because it doesn’t allow locks at all, and it doesn’t block I/O calls directly. Node also claims that the server running it can support tens of thousands of concurrent connections.

Node.js is not a JS application, but a JS running platform

Node.js is written in C++ and is a Javascript runtime environment. Why C++? Ryan Dahl, the founder of node.js, recalls that he initially wanted to write node.js in Ruby, but found that the Ruby virtual machine wasn’t performing as well as he wanted. He tried V8, so he chose C++ instead. If it’s not Javascript, why is it called.js? Because Node.js is a Javascript runtime environment. When it comes to Javascript, the first thing that comes to mind is the everyday browser. Modern browsers contain various components, including rendering engines, Javascript engines, etc. Javascript engines are responsible for interpreting and executing Javascript code in web pages. As one of the most important languages for the Web front-end,Javascript has always been the preserve of front-end engineers. However, Node.js is a back-end Javascript runtime environment (Linux, Windows), which means you can write system-level or server-side Javascript code and hand it to Node.js to interpret execution with simple commands like:

 # node helloworld. JsCopy the code

Node.js is powered by the V8 engine of Google Chrome, which provides excellent performance and many system-level apis, such as file manipulation and network programming. Browser-side Javascript code is limited by various security restrictions when running, and has limited operation on the client system. By contrast, Node.js is a full-fledged background runtime that provides Javascript with many of the capabilities that other languages can.

4 Node.js adopts event-driven, asynchronous programming and is designed for network services

The term event-driven is familiar. In some traditional network programming languages, we use callback functions, such as the registered callback function will be executed when the socket resource reaches a certain state. Event-driven is the core of Node.js design, and most of its apis are event-based and asynchronous. Taking the Net module as an example, the net.socket object has the following events: Connect, data, end, timeout, drain, error, close, etc. Developers using Node.js need to register the corresponding callback function according to their own business logic. These callbacks are executed asynchronously, which means that although they appear to be registered sequentially in the code structure, they do not depend on the order in which they appear, but rather wait for events to fire. An important advantage of an event-driven, asynchronous programming design is that it makes full use of system resources, so that code execution does not have to block and wait for an operation to complete, and limited resources can be used for other tasks. This kind of design is ideal for back-end web service programming, and node.js aims to do just that. Concurrent request processing is a big problem in server development, and blocking functions can lead to wasted resources and time delays. Through event registration, asynchronous functions, developers can improve resource utilization and performance.

From the support modules provided by Node.js, we can Many functions, including file operations, are executed asynchronously, which is different from traditional languages. Moreover, in order to facilitate server development,Node.js has many network modules, including HTTP, DNS, NET, UDP, HTTPS, TLS, etc. Developers can quickly build Web servers on this basis. Take the simple helloworld.js example:

// The global require() method is used to import modules, usually by assigning the return value of require() directly to a variable that can be used directly in JavaScript code. Require (" HTTP ") is the HTTP module that loads the system preset.var http = require('http');

// http.createServer is the module's method to create and return a new Web Server object and bind a callback to the service to handle the request.
http.createServer(function (req, res) {
    // Use response.writehead () to send an HTTP status 200 and the content-type of the HTTP header.
    // Use response.write() to send the text "Hello World" in the corresponding HTTP body
    res.writeHead(200, {'Content-Type': 'text/plain'});
    // Complete the response
    res.end('Hello World\n');
// The HTTP server listens on a specific port with the http.listen() method.
}).listen(80."127.0.0.1");

// console.log without further ado, anyone who knows Firebug should know that Node implements this method.
console.log('Server running at http://127.0.0.1:80/);
Copy the code

The above code sets up a simple HTTP server (running the sample deployment) Available at http://127.0.0.1), listens locally on port 80. For any HTTP request, the server returns a “Hello World” literal response with a header status code of 200 and a content-type value of ‘text/plain’. From this small example, we can see several things:

  • Node.js makes network programming easier, providing modules (HTTP in this case) that open up easy-to-use apis and allow you to build servers in just a few lines of code.
  • Event-driven, asynchronous programming, the createServer parameter specifies a callback function (implemented in Javascript anonymously) that node.js invokes when an HTTP request is sent in to handle the request and respond to it. Of course, this example is relatively simple, without too many event registrations, and readers will see more practical examples in future articles.

When we use the http.createserver method, of course we don’t just want a server listening on a port, we also want it to do something when the server receives an HTTP request. The problem is, this is asynchronous: requests can arrive at any time, but our server is running in a single process. We created the server and passed a function to the method that created it. This function is called whenever our server receives a request.

Why is this event-driven ideal for Node? JavaScript is a great event-driven programming language because it allows anonymous functions and closures and, more importantly, its syntax is familiar to anyone who has written code. The callback function that is called when an event occurs can be written where the event is captured. This makes code easy to write and maintain, without complex object-oriented frameworks, interfaces, and the possibility of over-design. Just listen for the event, write a callback function, and leave the rest to the system!

5 Features of Node.js

Let’s talk about the features of Node.js. The nature of event-driven, asynchronous programming has been covered in detail and will not be repeated here.

Node.js performs well. According to founder Ryan Dahl, performance is an important consideration in node.js, and the choice of C++ and V8 over Ruby and other virtual machines is based on performance. Node.js is also bold in its design, running in single-process, single-threaded mode (surprise, right? This is the same as Javascript), the event-driven mechanism is realized by node.js through the internal single thread efficiently maintain the event loop queue, no multi-thread resource consumption and context switch, which means that in the face of large-scale HTTP requests, Node.JS by event-driven everything, accustomed to the traditional language network Web service developers may be familiar with multi-threaded concurrency and collaboration, but with Node.js, we need to accept and understand its features. Can we infer from this that this design causes the load to be concentrated on the CPU(event loop processing? (Remember the days when the Java virtual machine threw an OutOfMemory exception?) , seeing is believing, let’s take a look at the performance test of Node.js by the Team of Taobao Shared data Platform:

  • Physical server configuration :RHEL 5.2, 2.2GHz CPU, 4 GB memory
  • Node.js application scenario :MemCache agent, which fetches 100 bytes of data each time
  • Connection pool size :50
  • The number of concurrent users is 100
  • Test results (Socket mode): memory (30M), QPS(16700), CPU(95%)

From the above results, we can see that in this test scenario, QPS was up to 16,700 times, memory usage was only 30M(of which the V8 heap was 22M), and CPU was up to 95%, potentially a bottleneck. In addition, there are a number of practitioners who have done performance analysis on Node.js, and in general, its performance is convincing and a major reason for its popularity. Since Node.js adopts single-process and single-thread mode, how can Node.js with outstanding single-core performance make use of multi-core CPU in today’s multi-core hardware popular environment? Founder Ryan Dahl suggested running multiple Node.js processes and using some kind of communication mechanism to coordinate tasks. Several third-party Node.js multi-process support modules have been released, and future articles will cover node.js programming on multi-core cpus in more detail.

Another feature of Node.js is that it supports Javascript. The pros and cons of dynamic versus static languages are not discussed here. Just three points:

  1. As the main language of front-end engineers, Javascript has considerable appeal in the technical community. Moreover, with the continuous development of Web technology, especially the increasing importance of the front end, many front-end engineers began to try the water of “background application”. In many enterprises that use Node.js, engineers say that because they are used to Javascript, they choose Node.js.
  2. Javascript’s anonymous functions and closures are ideal for event-driven, asynchronous programming, and as you can see from the HelloWorld example, callbacks are conveniently implemented in the form of anonymous functions. Closures are even more useful, as shown in the following code example:
var hostRequest = http.request(requestOptions,function(response) {
    var responseHTML =' '; 
    response.on('data'.function (chunk) {
        responseHTML = responseHTML + chunk;    
    });
    response.on('end'.function(){ 
       console.log(responseHTML);
       // do something useful
    });
});
Copy the code

In the code above, we need to handle the responseHTML variable in the end event, Because of the closure nature of Javascript, we can define the responseHTML variable outside of the two callback functions, then continually modify its value in the data event’s corresponding callback function, and finally access the processing in the end event.

  1. Javascript has better performance in dynamic languages. Some developers have conducted performance analysis on dynamic languages such as Javacript, Python and Ruby, and found that the performance of Javascript is better than that of other languages. In addition, V8 engine is also the best in the same category, so the performance of Node.js is also benefited. Node.js was chosen for a number of reasons, including interest and community development, as well as a desire to increase concurrency and drain CPU resources.