What exactly is Node.js? What's the benefit of node.js? _node.js

Source: Internet
Author: User
Tags anonymous generator php server

Node is a server-side JavaScript interpreter that will change the concept of how the server should work. Its goal is to help programmers build highly scalable applications and write connection codes that handle tens of thousands of simultaneous connections to one (only one) physical machine.

Brief introduction

If you've ever heard of node, or read some articles about how awesome node is, you might think, "What is node?" "Even after you see the home page of node, you may not even understand what node is?" Node is certainly not for every programmer, but it may be something that some programmers have been searching for.
To try to explain what node.js is, this article will briefly introduce some background information: it's about the problem, how it works, how to run a simple application, and finally, where Node is a good solution. This article does not cover how to write a complex node application, nor is it a comprehensive node tutorial. Reading this article should help you decide whether you should continue to learn Node so that it can be used in your business.

What problem does Node aim to solve?

Node's avowed goal is "to provide a simple way to build a scalable network program." What is wrong with the current server program? Let's do a maths problem. In languages such as Java™ and PHP, each connection generates a new thread, and each new thread may require 2 MB of matched 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. This, of course, increases costs such as server costs, traffic costs, and labor costs. In addition to these rising costs, there is a potential technical problem that a user may use a different server for each request, so any shared resource must be shared across all servers. For all of these 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 handle.
Node solves this problem by changing how you connect to the server. Instead of generating a new OS thread (and allocating some supporting memory for each connection), each connection launches an event that runs in the Node engine's process. Node claims that it will never deadlock because it does not allow locks at all, and it does not block I/O calls directly. Node also claims that the server running it can support tens of thousands of concurrent connections.
Now that you have a program that can handle tens of thousands of concurrent connections, what can you actually build with Node? If you have a WEB application that needs to handle so many connections, it will be a very "scary" thing! It's a question of "If you have this problem, then it's not a problem at all." Before answering the above question, let's take a look at how Node works and how it is designed to run.

Node is definitely not what?

Yes, Node is a server program. However, the underlying Node product is certainly not like Apache or Tomcat. Essentially, those servers are "installed Ready" server products that support the immediate deployment of applications. With these products, you can start and run a server in a minute. Node is definitely not the product. Similar to the idea that Apache can add a PHP module to allow developers to create dynamic Web pages and add an SSL module to secure connections, node also has a module concept that allows modules to be added to the node kernel. In fact, there are more than hundreds of modules available for Node, and communities are very active in creating, publishing, and updating modules, and can even process dozens of modules a day. The entire module section of Node is discussed later in this article.

How does Node work?

Node itself runs V8 JavaScript. Wait, JavaScript on the server? Yes, you are not mistaken. Server-side JavaScript may be a new concept for programmers who use JavaScript only on the client, but the concept itself is not remote, so why not use the programming language on the client on the server?
What is V8? The V8 JavaScript engine is the underlying JavaScript engine that 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 ultrafast interpreter written in C + + that has another unique feature; you can download the engine and embed it in any application. The V8 JavaScript engine is not limited to running in one browser. Therefore, Node actually uses the V8 JavaScript engine written by Google and rebuilds it to be available on the server. It's perfect! Why create a new language if you already have a good solution available?

Event-driven programming

Many programmers are taught that object-oriented programming is the perfect programming design, making them dismissive of other programming methods. Node uses a so-called event-driven programming model.

Listing 1. Event-driven programming with JQuery on the client

Copy Code code as follows:

JQuery code on the client-side showing how Event-driven programming works

When a button was pressed, an Event occurs-deal with it
Directly right this is the 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 side and the client. Yes, there's no button click Action, no action to type into the text field, but at a higher level, the event is happening. A connection is built, this is an event! Data is received through a connection, which is also an event! Data is stopped by a connection, which is an event!
Why is this type of Setup ideal for Node? JavaScript is a great event-driven programming language because it allows anonymous functions and closures, and more importantly, anyone who has written code is familiar with its syntax. Callback functions that are invoked when an event occurs can be written at the capture event. This makes code easy to write and maintain, without complex object-oriented frameworks, without interfaces, without the possibility of excessive design. Just listen to the event, write a callback function, other things can be given to the system to deal with!

Sample Node Application

Finally, let's look at some code! Let's summarize all the things we've discussed to create our first Node application. We already know that Node is ideal for handling high-traffic applications, so we're going to create a very simple WEB application, an application built to achieve the fastest speed. Here's what the "Boss" has to tell us about our sample application: Create a random number generator RESTful API. This application should accept an input: A parameter named "number". The application then returns a random number between 0 and the parameter, and returns the generated number to the caller. Because "Boss" wants the application to be 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

Copy Code code as follows:

These modules need to is imported in order to use them.
Node has several modules. They are like any #include
Or import statement in the other languages
var http = require ("http");
var url = require ("url");

The most important line in any Node file. This function
Does the actual process of the creating the server. Technically,
Node tells the underlying operating system that whenever a
Connection is made, this particular callback function should to 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 be callback method receives a ' request '
and ' response ' object automatically. This should is familiar
to any PHP or Java programmer.
Http.createserver (function (request, response) {

    //The response needs to handle all headers, and the return codes
   &N Bsp These types of things are handled automatically into server programs
    //Like Apache and TOMC At, but Node requires everything to being done yourself
     response.writehead ("Content-type" : "Text/plain"});

    //Here are some unique-looking code.  this are how Node retrives
   &NB Sp Parameters passed in from client requests.  URL module
    //Handles all of these funct ions.  the parse function
    //deconstructs the URL, and places the query key-values in th E
    //query object.  We can find the value for the "number" key
   &NB Sp 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'll create
    //O ur random number that gets passed the caller
     var numinput = new number (input);
&N bsp;    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.  T The He is because
    //Node allows you to keep a connection open and pass data back and forth,
    //Though that advanced topic isn ' t discussed into this article.
     Response.End ();

When we create the server, we have to explicitly connect the HTTP server to
A port. Standard HTTP Port is and 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 correctly
Console.log ("Random number generator Running ...");

Start the application

Put the above code in a file called "Random.js". Now, to start the application and run it (to create an HTTP server and listen for a connection on port 80), simply enter the following command in your command prompt:% node random.js. Here's what the server looks like when it's started and runs:

Copy Code code as follows:

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

accessing applications

The application has started and is running. Node is listening to all the connections, let's test it. Because we have created a simple RESTful API, we can use a Web browser to access this application. Type the following address (make sure you have completed the steps above): Http://localhost/?number=27.
Your browser window will change to a random number between 0 and 27. Click the Reload button on the browser and you will get another random number. That's it, that's your first Node application!

What is Node good for?

So far, you might be able to answer the question "What node is," but you might have another question: "What's the Use of node?" "This is an important issue that needs to be raised, because certain things can benefit from Node."

What is it good for?

As you've seen before, Node is ideal for situations where you expect to have a high flow of traffic before responding to a client, but not necessarily a lot of server-side logic and processing required. Typical examples of Node performance include:

RESTful API

WEB services that provide the RESTful API receive several parameters, parse them, combine a response, and return a response (usually less text) to the user. This is ideal for Node because you can build it to handle tens of thousands of of connections. It still doesn't require a lot of logic; it essentially looks for values from a database and makes them a response. Because the response is a small amount of text, inbound requests are small amounts of text, so traffic is not high, and a machine can even handle the API requirements of the busiest company.

Twitter queue

Imagine a company like Twitter that must receive tweets and write them to the database. In fact, with almost thousands of tweets per second, it is not possible for the database to handle the number of writes required during peak periods. Node becomes an important part of the solution to this problem. As you can see, Node handles tens of thousands of inbound tweets. It can quickly and easily write them to a memory queuing mechanism (such as memcached), where another individual process can write them to the database. Node's role here is to quickly collect tweets and pass this information on to another process that is responsible for writing. Imagine another design (a regular PHP server will try to handle writing to the database itself): Each tweet will cause a short delay when writing to the database because the database call is blocking the channel. Due to database latency, a machine of this design may only handle 2000 inbound tweets per second. 500 servers are required to process 1 million tweets per second. Instead, Node can handle each connection without blocking the channel, allowing it to capture as many tweets as possible. A Node machine that can handle 50,000 tweets requires only 20 servers.

Video game statistics

If you play "Call of Duty" game online, when you look at the game statistics, you will immediately realize a problem: to generate that level of statistics, you must track the mass of information. In this way, if millions of players play the game online at the same time, and they are in different positions in the game, then a huge amount of information will soon be generated. Node is a good solution to this scenario because it captures game-generated data, merges the data to the minimum, and queues the data to write to the database. Using the entire server to track how many bullets the player fired in the game looks silly, if you use a server like Apache, there may be some useful limitations, but conversely, if you use a server specifically to track all the statistics for a game, as you do with a server running Node , that seems like a sensible move.

Node Module

Although not the topic originally discussed in this article, this article has been extended to include a profile of node Modules and node Package Manager at the request of the general reader. As with developers who are accustomed to using Apache, you can also extend Node functionality by installing modules. However, the modules that are available for node greatly enhance the product, and those modules are very useful, and developers who will use node typically have several modules installed. Therefore, the module becomes more and more important and even becomes a key part of the whole product.
In the Resources section, I provide a link to the module page that lists all the available modules. To demonstrate the possibilities that the module can offer, I've included the following modules in dozens of available modules: one for writing dynamically created pages (such as PHP), one for simplifying MySQL usage, one for helping with WebSockets, and a module for assisting text and parameter parsing. I'm not going to go into these modules in detail, because this overview article is designed to help you understand Node and determine if you need to go deep (again), and if you do, you'll have the opportunity to use these available modules.

In addition, one of node's features is node Package module, which is a built-in feature for installing and managing node modules. It handles dependencies automatically, so you can be sure that any modules that you want to install will be installed correctly and contain the 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 way to allow easy extension of the node functionality without worrying about damaging your node installation. Similarly, if you choose to delve into node, NPM will be an important part of your node solution.

Conclusion

After reading this article, the question you encountered at the beginning of this article, "What the hell is Node.js?" should have been answered, and you should be able to answer the question in a few clear and concise sentences. If so, you have come to the fore of many programmers. I've talked to a lot of people about node, but they've been confused about what node is doing with it. Understandably, they have the Apache way of thinking that the server is an application that puts the HTML files into it and everything works. Since most programmers are familiar with Apache and its purpose, the easiest way to describe Node is to compare it to Apache. node is a program that can accomplish all the tasks that Apache can accomplish (with some modules) and, as a scalable JavaScript platform that can be built as a foundation, node can do more of the work.
As you can see from this article, Node completes its goal of providing a highly scalable server. It uses Google's one very fast JavaScript engine, the V8 engine. 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, where it becomes easier to write a highly scalable solution.

As important as understanding Node is, understanding what it is not. Node is not just an alternative to Apache, it is designed to make PHP Web applications easier to scale. This is far from the truth. Although Node is still in its infancy, it develops very quickly, community participation is very high, community members create a large number of excellent modules, within a year, this evolving product is likely to appear in your business.

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.