Introduction to node. js

Source: Internet
Author: User
Tags php server

This is an article about node. js. I personally think it is very good, especially it clarifies why the framework of node. JS is like this.

Original address: CA = Drs-

What problems does node solve:

The goal publicly stated by node is "to provide a simple method for building scalable network programs ". What is the problem with the current server program? Let's make a math. In languages such as Java and PHP, each connection generates a new thread, and each new thread may require 2 MB of memory. In a system with 8 gb ram, theoretically the maximum number of concurrent connections is 4,000. As your customer base grows, if you want your web applications to support more users, you must add more servers. Of course, this will increase the costs of servers, traffic, and labor. In addition to these increases in costs, there is also a potential technical problem: users may use different servers for each request. Therefore, any shared resource must be shared among all servers. For all of the above reasons, the entire
The bottleneck in the Web application architecture (including traffic, processor speed, and memory speed) is the maximum number of concurrent connections that the server can process.

Node can solve this problem by changing the connection method to the server. Each connection emits an event running in the node engine process, instead of generating a new OS thread for each connection (and allocating some supporting memory ). Node claims that it will never be deadlocked because it does not allow the use of locks at all, and it will not directly block I/O calls. Node also claims that its server can support tens of thousands of concurrent connections.

Now that you have a program that can process tens of thousands of concurrent connections, what can you build with node? If you have a web application that needs to process so many connections, it will be a terrible thing! It is a problem of "if you have this problem, it is not a problem at all. Before answering the above questions, let's take a look at the working principle of node and its design and running mode.

Node is definitely not something?

Node itself runs V8 JavaScript. Wait, the JavaScript on the server? No, you are not mistaken. For programmers who only use JavaScript on the client, server-side JavaScript may be a new concept, but this concept is not out of reach, so why cannot I use the programming language on the client on the server?

What is V8? V8 JavaScript engine is the underlying JavaScript engine Google uses for its Chrome browser. Few people think about what JavaScript actually does on the client? In fact, the JavaScript engine is responsible for interpreting and executing code. Google uses V8 to create an ultra-fast interpreter written in C ++, which has another unique feature. You can download the engine and embed itAnyApplication. The V8 JavaScript engine is not limited to running in a browser. Therefore, node will actually use V8 compiled by Google
Javascript engine, and re-build it for use on the server. Perfect! Since there is already a good solution available, why should we create a new language?

Event-driven programming model

The education given to many programmers makes them think that object-oriented programming is a perfect programming design, which makes them dismissive of other programming methods. Node uses a so-called event-driven programming model.

// jQuery code on the client-side showing how Event-Driven programming works// When a button is pressed, an Event occurs - deal with it// directly right here in an anonymous function, where all the// necessary variables are present and can be referenced directly$("#myButton").click(function(){     if ($("#myTextField").val() != $(this).val())         alert("Field must match button text");});

In fact, there is no difference between the server and the client. Yes, there is no button to click or type in the text field, but at a higher level, the eventIsOccurred. A connection is established. This is an event! Data is received through a connection. This is also an event! Data is stopped by connection. This is still an event!

Why is this setting type ideal for node? Javascript is a great event-driven programming language because it allows anonymous functions and closures. More importantly, anyone who has written code is familiar with its syntax. The callback function called when an event occurs can be written at the capture event. This makes the code easy to write and maintain without complicated object-oriented frameworks, interfaces, and the possibility of over-design. You only need to listen to the event and write a callback function. Other tasks can be handled by the system!

Node sample application:

Finally, let's look at some code! Let's summarize all the discussed content to create our first node application. We already know that node is ideal for processing high-traffic applications, so we will create a very simple web application and an application built to achieve the fastest speed. The following are the specific requirements of our sample application described by the "boss": Create a random number generator restful API. This application should accept an input named
Number parameter. Then, the application returns a random number between 0 and this parameter, and returns the generated number to the caller. Because the "boss" wants the application to become a popular application, it should be able to handle 50,000 concurrent users. Let's take a look at the following code:

// these modules need to be imported in order to use them.// Node has several modules.  They are like any #include// or import statement in other languagesvar http = require("http");var url = require("url");// The most important line in any Node file.  This function// does the actual process of creating the server.  Technically,// Node tells the underlying operating system that whenever a// connection is made, this particular callback function should be// executed.  Since we're creating a web service with REST API,// we want an HTTP server, which requires the http variable// we created in the lines above.// Finally, you can see that the callback method receives a 'request'// and 'response' object automatically.  This should be familiar// to any PHP or Java programmer.http.createServer(function(request, response) {     // The response needs to handle all the headers, and the return codes     // These types of things are handled automatically in server programs     // like Apache and Tomcat, but Node requires everything to be done yourself     response.writeHead(200, {"Content-Type": "text/plain"});     // Here is some unique-looking code.  This is how Node retrives     // parameters passed in from client requests.  The url module     // handles all these functions.  The parse function     // deconstructs the URL, and places the query key-values in the     // query object.  We can find the value for the "number" key     // by referencing it directly - the beauty of JavaScript.     var params = url.parse(request.url, true).query;     var input = params.number;     // These are the generic JavaScript methods that will create     // our random number that gets passed back to the caller     var numInput = new Number(input);     var numOutput = new Number(Math.random() * numInput).toFixed(0);          // Write the random number to response     response.write(numOutput);          // Node requires us to explicitly end this connection.  This is because     // Node allows you to keep a connection open and pass data back and forth,     // though that advanced topic isn't discussed in this article.     response.end();   // When we create the server, we have to explicitly connect the HTTP server to   // a port.  Standard HTTP port is 80, so we'll connect it to that one.}).listen(80);// Output a String to the console once the server starts up, letting us know everything// starts up correctlyconsole.log("Random Number Generator Running...");

Put the above code into a file named "random. js. To start the application and run it (to create an HTTP server and listen to connections on port 80), simply enter the following command in your command prompt:% node random.js. The following figure shows what the server looks like when it is started and running:

root@ubuntu:/home/moila/ws/mike# node random.jsRandom Number Generator Running...

The application has been started and running. Node is listening for all connections. Let's test it. Because we have created a simple restful API, we can use a web browser to access this application. Enter the following address (make sure you have completed the preceding steps): http: // localhost /? Number = 27.

Your browser window will be changed to a random number between 0 and 27. Click "reload" in the browser to get another random number. This is the first node application!

What are the benefits of node?

So far, you may be able to answer the question "What is node", but you may have another question: "What is the purpose of Node ?" This is an important question that needs to be raised, because something can benefit from node. As you have seen before, node is very suitable for the following situations: before responding to the client, you may expect high traffic, but the server logic and processing required are not necessarily great. Typical examples of outstanding node performance include:

The Web service that provides restful APIs receives several parameters, parses them, combines a response, and returns a response (usually less text) to the user. This is ideal for node because you can build it to process tens of thousands of connections. It still does not require a lot of logic; in essence, it simply finds some values in a database and forms a response. Because the response is a small amount of text, the inbound request is also a small amount of text, so the traffic is not high, a machine can even handle the API requirements of the busiest companies.

Twitter queue:Imagine
A company like Twitter must receive tweets and write them into the database. In fact, there are almost thousands of Tweets per second, and the database cannot process the number of writes required during peak hours in a timely manner. Node becomes an important part of the solution to this problem. As you can see, node can process tens of thousands of inbound tweets. It can quickly and easily write them into a memory queuing mechanism (such as memcached) from where another independent process can write them into the database. Node's role here is to quickly collect tweet and pass this information to another write process. Imagine another design (the regular PHP server will try to write data to the database itself ):
Tweet will cause a short delay when writing data to the database because the database call is blocking the channel. Due to database latency, a machine designed in this way can only process 2000 inbound Tweets per second. 1 million servers are required to process 500 Tweets per second. On the contrary, node can process each connection without blocking the channel, so as to capture as many tweets as possible. Only 20 servers are required for a node machine that can process 50,000 tweets.

Online Game data statistics:If you have played the Call of Duty game online, When you view the Game statistics, you will immediately become aware of the problem: to generate statistics at that level, you must track massive amounts of information. In this way, if millions of gamers play games online at the same time and they are in different positions in the game, a massive amount of information will soon be generated. Node is a good solution for this scenario, because it can collect game-generated data, merge the data at least, and then queue the data to write them into the database. Using the entire server to track how many bullets a player has fired in the game looks silly if you use
Servers such as Apache may have some useful restrictions. However, if you use a server to track all the statistics of a game, as the server running node does, it seems wise.

Node Module

Although it is not the topic discussed in the first part of this article, this article has been extended to include a node modules and node Package Manager Introduction At the reader's request. Just as you are used to using Apache
You can also use the installation module to expand node functions. However, the modules that can be used for node greatly enhance this product. Those modules are very useful and will use node
Developers usually install several modules. Therefore, modules become more and more important, and even become a key part of the entire product.

In "references"
Section, I provide a link to the module page, which lists all available modules. To demonstrate the possibilities provided by the module, I have included the following modules in dozens of available modules: one for writing dynamically created pages (such as PHP) and the other for simplifying MySQL usage, one module is used to help use websockets, and the other is used to assist in text and Parameter Parsing. I will not describe these modules in detail, because this overview article aims to help you understand node and determine whether you need to learn it in depth (again). If necessary, you will certainly have the opportunity to use these available modules.

In addition
One feature of is the node package module, which is a built-in function used to install and manage the node module. It automatically processes dependencies, so you can be sure that any module you want to install will be correctly installed and contain necessary dependencies. It also supports publishing your own modules to the node community, if you choose to join the Community and write your own modules. You can think of NPM as a method that allows you to easily expand the node function without worrying about this will damage your node installation. Similarly, if you choose to study node in depth, NPM will be an important part of your node solution.


Node. js
The home page is the entry point for understanding this application.

View node. js
API page. Note that the syntax for different releases may be different. Therefore, carefully check the version you have downloaded and the API you are browsing.

See Node
Module page, which lists all modules that can be used in node.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.