What is Node. js? What are the advantages of Node. js? _ Node. js-js tutorial

Source: Internet
Author: User
Tags php server
This article mainly introduces what is Node. js? What are the advantages of Node. js ?, To try to explain what Node is. js, this article will briefly introduce some background information: the problem to be solved, how it works, how to run a simple application, and finally, what is a good solution for Node, if you need it, you can refer to Node as a server-side JavaScript interpreter, which will change the concept of how the server should work. It aims to help programmers build highly scalable applications and write connection code that can process tens of thousands of concurrent connections to one (only one) physical machine.

Introduction

If you have heard about Node, or read some articles about how awesome it is, you may think: "What is Node ?" Even after reading the Node homepage, you may not even understand what Node is? Node is definitely not suitable for every programmer, but it may be something that some programmers have been pursuing.
To try to explain what Node is. js, this article will briefly introduce some background information: the problem to be solved, how it works, how to run a simple application, and finally, under what circumstances is a good solution for Node. This article does not involve writing a complex Node application, nor is it a comprehensive Node tutorial. Reading this article should help you decide whether to continue learning Node for your business.

What is the purpose of Node?

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 Java™In PHP and other languages, 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 bottleneck in the entire 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?

Yes, Node is a server program. However, the basic Node product is definitely not like Apache or Tomcat. Essentially, those server "ready-to-use" Server products support immediate deployment of applications. With these products, you can start and run a server within one minute. Node is definitely not such a product. Apache can add a PHP module to allow developers to create dynamic Web pages and add an SSL module to implement secure connections. Similarly, Node also has the concept of a module, allows you to add modules to the Node kernel. In fact, there are hundreds of modules available for Node, and the Community is very active in creating, releasing, and updating modules. It can even process dozens of modules A Day. This article will discuss the entire module of Node later.

How does Node work?

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 it into any application. The V8 JavaScript engine is not limited to running in a browser. Therefore, Node will actually use the V8 JavaScript Engine compiled by Google and rebuild it to be used on the server. Perfect! Since there is already a good solution available, why should we create a new language?

Event-driven programming

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.

Listing 1. event-driven programming using jQuery on the client

The Code is as follows:


// 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
// 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 event is happening. 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!

Sample Node 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: a parameter named "number. 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:

Listing 2. Node random number generator

The Code is as follows:


// 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 ages
Var 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
// Connection is made, this particle callback function shocould 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 has es a 'request'
// And 'response' object automatically. This shoshould 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
// 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
// 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, lew.us know everything
// Starts up correctly
Console. log ("Random Number Generator Running ...");

Start the application

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), 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:

The Code is as follows:


Root @ ubuntu:/home/moila/ws/mike # node random. js
Random Number Generator Running...

Access applications

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.

What is its benefit?

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:

RESTful API

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 that must receive tweets and write it 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): Each 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.

Video Game 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. It looks silly to use the entire server to track how many bullets a player has fired in the game. If you use a server like Apache, there may be some useful restrictions; but on the contrary, if you use a server to track all the statistics of a game, just 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. As developers who are used to using Apache, you can also expand Node functions by installing modules. However, the modules that can be used for Node greatly enhance this product. Those modules are very useful. developers who will use Node usually install several modules. Therefore, modules become more and more important, and even become a key part of the entire product.
In the reference 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 Node is the Node Package Module, which is a built-in function for installing and managing Node modules. 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.

Conclusion

After reading this article, you have encountered the question "What is Node. js?" at the beginning of this article ?" The answer should have been answered. You should be able to answer this question in a few clear and concise sentences. If so, you have come to the forefront of many programmers. I have talked with many people about Node, but they are still confused about what Node is used. It can be understood that they have some ways of thinking in Apache, and think that the server is an application, put HTML files in it, everything will run normally. Since most programmers are familiar with Apache and its usage, the simplest way to describe Node is to compare it with Apache. Node is a program that can complete all the tasks that Apache can accomplish (using some modules), and serves as an extensible JavaScript platform that can be built on it as the basis, node can complete more tasks.
It can be seen from this article that Node has completed its goal of providing highly scalable servers. It uses Google's extremely fast JavaScript Engine, V8. It uses an event-driven design to keep the code minimal and easy to read. All of these factors contribute to the ideal goal of Node, that is, it is easier to write a highly scalable solution.

Just as important as understanding what Node is, understanding it is not. Node is not just a substitute for Apache. It aims to make PHP Web applications more scalable. This is far from the case. Although Node is still in its initial stage, it has developed rapidly and has a high degree of community engagement. community members have created a large number of excellent modules. Within one year, this evolving product may appear in your enterprise.

Related Article

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: info-contact@alibabacloud.com 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.