What is node. js

Source: Internet
Author: User
Tags php server

What is node. js

A "coded ready" 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 capable of handling tens of thousands of simultaneous connections to a single (one) physical machine.

What does Node aim to solve?

Node's avowed goal is "to provide a simple way to build scalable network programs." What is wrong with the current server program? Let's do a math problem. In Java? In languages such as PHP, each connection generates a new thread, and each new thread may require 2 MB of companion memory. On a system with 8 GB of RAM, theoretically the 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 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 these reasons, the bottleneck in the overall 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 the way it connects to the server. Each connection emits an event that runs in the Node engine's process instead of generating a new OS thread for each connection (and allocating some companion memory for it). Node claims that it will never deadlock, because it does not allow locks at all, and it does not directly block I/O calls. 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 through Node? If you have a WEB application that needs to handle so many connections, it would be a "scary" thing! It's a question of "If you have this problem, then it's not a problem at all." Before answering the above questions, let's look at how Node works and how it's designed to work.

Node is definitely not what?

Yes, Node is a server program. However, the underlying Node product is definitely not like Apache or Tomcat. Essentially, those servers are "ready-to-install" server products that support the immediate deployment of applications. With these products, you can start and run a server within a minute. Node is definitely not the product. Similarly, with the addition of a PHP module to allow developers to create dynamic Web pages and add an SSL module for secure connections, the node also has a modular concept that allows modules to be added to the node kernel. In fact, there are hundreds of modules available for Node, and the community is very active in creating, publishing, and updating modules, and can even handle 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 did not read wrong. Server-side JavaScript may be a new concept for programmers who use JavaScript only on the client, but the concept itself is not unreachable, so why can't I use the programming language on the client computer on the server?

What is V8? The 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 the code. Google uses V8 to create an ultra-fast interpreter written in C + + that has another unique feature that you can download and embed in any application. The V8 JavaScript engine is not limited to running in a single browser. As a result, 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 now that you have a good solution available?

Event-driven programming

The education that many programmers receive makes them think that object-oriented programming is the 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
// 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 side and the client. Yes, there is no button click action, and no action is typed into the text field, but at a higher level, the event is occurring. A connection was built, this is an event! The data is received through the connection, which is also an event! Data is stopped through the 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, and more importantly, anyone who writes code is familiar with its syntax. The callback function that is called when an event occurs can be written at the capture event. This makes code easy to write and maintain, with no complex object-oriented framework, no interfaces, and no over-design possibilities. Just listen to the event, write a callback function, and everything else can be handed to the system for processing!

Sample Node Application

Finally, let's look at some code! Let's summarize everything we've discussed to create our first Node application. We already know that Node is ideal for dealing with high-traffic applications, so we'll create a very simple WEB application, an application built for the fastest speed. Here's what the boss says 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 resulting number to the caller. Because the 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
These modules need to is imported in order to use them.//Node have several modules. They is like no #include//or import statement in other Languagesvar HTTP = require ("http"); var url = require ("url");//  The most important on any Node file.  This function//does the actual process of creating the server. technically,//Node tells the underlying operating system that whenever a//connection are made, this particular callback F  Unction 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 automatic  Ally. This should is familiar//to any PHP or Java programmer.http.createServer (function (request, response) {//the Respons E needs to handle all the headers, and the return codes//These types of things is handled automatically in server p Rograms//Like Apache and TomCat, but Node requires everything to is done yourself Response.writehead ($, {"Content-type": "Text/plain"});  Here is some unique-looking code.  This is what 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 is the generic JavaScript methods that would 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 your to keep aConnection 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 had to explicitly connect the HTTP server to/a port. Standard HTTP Port is a, so we'll connect it to that one.}). Listen;//Output a String to the console once the server starts up, letting us know everything//starts up Correctlyco Nsole.log ("Random number Generator Running ...");

  

Start the application

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

[Email protected]:/home/moila/ws/mike# node random.jsrandom number Generator Running.

  

Accessing the application

The application is up and running. Node is listening to all the connections, let's test it. Since 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 your browser and you'll get another random number. That's it, this is your first Node app!

What is Node good for?

So far, you may be able to answer the question "What node is", but you may have another question: "What does node do?" "This is an important question to ask because there are certain things that can benefit from Node.

What is it good for?

As you've seen before, Node is well-suited for scenarios where you expect a high level of traffic before responding to a client, but not necessarily a lot of server-side logic and processing required. Typical examples of Node's outstanding performance include:

    • RESTful API

WEB services that provide RESTful APIs 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 connections. It still does not require a lot of logic; it essentially simply looks up some values from a database and makes them a response. Because the response is small text, inbound requests are also small amounts of text, so traffic is not high, and a machine can even handle the API needs of the busiest companies.

    • Twitter queue

Imagine a company like Twitter that must receive tweets and write it to the database. In fact, almost thousands of tweets per second are achieved, and the database is not able to handle the number of writes required during peak hours in time. 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 queueing mechanism (such as memcached), where another individual process can write them to the database. Node's role here is to quickly gather tweets and pass this information to another process responsible for writing. Imagine another design (the regular PHP server will try to handle writes 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, which can capture as many tweets as possible. A Node machine that can handle 50,000 tweets requires only 20 servers.

    • Video game Stats

If you've played the Call of Duty game online, when you look at the game stats, you're immediately aware of the problem: to generate that level of statistics, you have to keep track of massive amounts of information. In this way, if millions of players play the game online at the same time, and they are in different places in the game, they will soon generate a huge amount of information. Node is a good solution for this scenario because it captures the game-generated data, merges the data in a minimal amount, and then queues the data to write them to the database. Using the entire server to track how many bullets the player has fired in the game looks foolish, and there may be some useful restrictions if you use a server like Apache, but instead, if you use a server specifically to track all the stats for a game, as you would with a server running Node , it seems like a smart move.

Node Module

Although not the topic originally planned for this article, this article has been extended to include a node Modules and node package Manager profile, as required by a broad audience. As developers who are accustomed to using Apache, you can also extend the functionality of Node by installing modules. However, the modules that are available for node greatly enhance the product, and those modules are very useful, and developers who use node will typically install several modules. As a result, modules become increasingly important and even a key part of the entire product.

In the Resources section, I provide a link to the module page, which lists all available modules. To demonstrate the possibilities that the module can provide, I have included the following modules in dozens of available modules: one for writing dynamically created pages (like PHP), one for simplifying MySQL usage, one for helping with WebSockets, and one for assisting with text and parameter parsing. I won't go into these modules in detail, because this overview article is designed to help you understand Node and determine if you need to learn more (again), and if you need to, you will definitely have the opportunity to use these available modules.

In addition, one feature of node is the node package module, a built-in feature for installing and managing node modules. It automatically processes dependencies, so you can be sure that any modules that you want to install will install 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 you to easily extend node functionality without worrying about damaging your node installation. Similarly, if you choose to learn more about node, NPM will be an important part of your node solution.

Conclusion

After reading the question that you encountered at the beginning of this article, "What exactly is node. js?" should have been answered, you should be able to answer this question in a few clear and concise sentences. If so, you've come to the front of many programmers. I've talked to a lot of people about node, but they've been confused about exactly what node is used to do. Understandably, they have the Apache way of thinking, that the server is an application, the HTML file into it, everything will work. Since most programmers are familiar with Apache and its purpose, the simplest way to describe Node is to compare it to Apache. node is a program that can accomplish all of the tasks that Apache can accomplish (with some modules) and, as an extensible JavaScript platform that can be built as a basis, node can do even more tasks.

As you can see from this article, Node completes its goal of providing a highly scalable server. It uses Google's 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 Node's ideal goal of writing a highly scalable solution that makes it easier.

It's just as important to understand what Node is , to understand what it is not . Node is not just a substitute for 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 has grown very quickly, community engagement is very high, community members have created a number of good modules, and within a year, this evolving product is likely to appear in your business.

..



What is node. js

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.