What is node. js?

Source: Internet
Author: User

Http://www.ibm.com/developerworks/cn/opensource/os-nodejs/

What is node. js?

A "encoding ready" Server

Michael abernethy, freelance programmer, freelancer

Michael abernethy has been dealing with a variety of different technologies and clients over his 13 years of technical career. He is currently a free programmer and is good at Java high availability and jquery. He is now focusing on rich Internet applications, trying to implement the complexity and simplicity of applications at the same time. He often plays golf in his spare time. More specifically, he finds him playing a golf ball in the bush.

Introduction:Node is a server-side javascript interpreter that will change how the server works. 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.

Average score (308 scores)
Score for this article

Editor's Note

After the first version of this article is published, the various points mentioned in this article have aroused wide discussion in the community. Therefore, the author of this article revised the first version, which draws on the points raised by community members. This peer review and discussion is a key part of the open source world. I would like to thank those colleagues who have made constructive comments.

Like all open-source projects, node. js will continue to develop and developers will explore new resources and new technologies that can overcome any limitations. By convention, we encourage readers to try new technologies in person.

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 evenOrWhat is node? 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.

Back to Top

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 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.

Back to Top

Node is definitely not something?

Yes, node is a server program. However, the basic node product is certainlyNoSuch as Apache or tomcat. In essence, the "ready-to-use" Server products of those servers 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 be discussed later
Node.

Back to Top

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 itAnyApplication. The V8 JavaScript engine is not limited to running in a browser. Therefore, node actually uses
V8 JavaScript Engine and rebuilding it for use on servers. 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

// 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!

Back to Top

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"
The application is expected to become a popular application, so it should be able to process 50,000 concurrent users. Let's take a look at the following code:

Listing 2. node random number generator

// 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...");

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

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!

Back to Top

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 ):
    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 dedicated server to track all the statistics of a game, it is like running
    As the node server does, it seems wise.

Back to Top

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 module that can be used for NodeGreatlyBy enhancing this product, those modules are very useful. developers who will use node will 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.

Back to Top

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 do (with some modules), and as a scalable JavaScript platform that can be built based on it, 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.

Understanding NodeYesWhat is equally important is understanding itNoWhat. 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.

References

Learning

  • The node. js homepage is the entry point for understanding this application.

  • Download node. js here. You will also need
    Python.

  • Browse the 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 the node module page, which lists all modules that can be used in node.
  • Search for NPM to easily expand the features installed by your node.
  • Stay tuned to developerworks
    Technical activities and network broadcasts.

  • Visit developerworks
    The Open Source Area provides rich how-to information, tools, and project updates, as well as the most popular articles and tutorials to help you develop with open source code technology, they are used in combination with IBM products.

  • See the free developerworks demonstration center and learn about IBM and open-source technologies and product features.

Obtain products and technologies

  • See the ever-changing
    List of open-source software packages.

  • Use the IBM product evaluation trial software to improve your next open-source development project, which can be downloaded.

Discussion

  • Participate in the forum.

  • Help build the developerworks community
    Real-world open source discussion group.

  • Join the Chinese community on developerworks. The community on developerworks is a professional social networking community that provides community functions such as blogs, bookmarks, wiki, groups, contacts, sharing and collaboration for IT professionals around the world.
  • Join
    IBM software download and technical exchange group to participate in online communication.

About the author

Michael abernethy has been dealing with a variety of different technologies and clients over his 13 years of technical career. He is currently a free programmer and is good at Java high availability and jquery. He is now focusing on rich Internet applications, trying to implement the complexity and simplicity of applications at the same time. He often plays golf in his spare time. More specifically, he finds him playing a golf ball in the bush.

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.