What is Node.js? Node.js Detailed Introduction _node.js

Source: Internet
Author: User
Tags anonymous generator php server node server tomcat

Brief introduction

If you've ever heard of node, or read some articles about how awesome node is, you might think, "What is node?" "Although not for everyone, Node may be the right choice for some people," he said.

To try to explain what node.js is, this article explores the problems it solves, how it works, how to run a simple application, and, finally, when and when Node is not 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 study Node in order to use it for 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 client base grows, you want your Web application to support more users, so you must add more servers. Of course, this increases business costs, especially server costs, transportation costs, and labor costs. In addition to these costs, there is a technical problem: Users may use a different server for each request, so any shared resource must be shared across all servers. For example, in Java, static variables and caching need to be shared between JVMs on each server. This is the bottleneck in the entire Web application architecture: The maximum number of concurrent connections a server can handle.

Node solves this problem by changing how the connection is connected to the server. Each connection creates a process that does not require a supporting block of memory, instead of generating a new OS thread for each connection (and allocating some supporting memory to it). 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. In fact, Node changes the server face by changing bottlenecks in the entire system from the maximum number of connections to the flow of a single system.

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 look at how Node works and how it is designed to run.

Node is definitely not something.

Yes, Node is a server program. However, it certainly does not look like Apache or Tomcat. Those servers are stand-alone server products, and you can install and deploy applications immediately. With these products, you can start and run a server in a minute. Node is definitely not the product. Apache can add a PHP module to allow developers to create dynamic Web pages, using TOMCAT programmers to deploy JSPs to create dynamic Web pages. Node is definitely not this type.

In the early stages of Node (currently version 0.4.6), it is not a "ready to run" server program, you cannot install it, place files in it, and have a full-featured Web server. Even if you want to implement a Web server to start and run this basic functionality after the installation is complete, there is still a lot of work to do.

How Node Works

Node itself runs V8 JavaScript. Wait, JavaScript on the server? Yes, you are not mistaken. Server-side JavaScript is a relatively new concept, as mentioned in the discussion of Aptana Jaxer products on developerWorks about two years ago (see Resources). Although Jaxer has never really been popular, the idea itself is not remote-why not use the programming language on the client on the server?

What makes V8? The V8 JavaScript engine is the underlying JavaScript engine that Google uses for their Chrome browsers. Few people think about what JavaScript actually does on the client. In fact, the JavaScript engine is responsible for interpreting and executing code. Use V8,google to create an ultrafast interpreter written in C + + that has another unique feature that you can download and embed in any application. It is not limited to running in one browser. Therefore, Node actually uses the V8 JavaScript engine written by Google and rebuilds it for use on the server. It's perfect! Why create a new language if you already have a good solution available?

Event-driven programming

Many programmers received education that led them to believe that object-oriented programming was the perfect programming design and 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 was built--event! Data received via connection-event! Data is stopped through the connection-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. In this way, code is easy to write and maintain, with no complex object-oriented framework, no interfaces, and no potential to structure any content above. Just listen to the event, write a callback function, and then event-driven programming will take care of everything!


Sample Node Application

Finally, let's look at some code! Let's combine all the things we've discussed and create our first Node application. Since we already know that Node is ideal for handling high-traffic applications, we are creating a very simple Web application-an application built to achieve maximum 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 it to be a popular application, it should be able to handle 50,000 concurrent users. Let's take a look at the 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 the headers, and the return codes
This types of things are handled automatically in server programs
Like Apache and Tomcat, but Node requires everything to being done yourself
Response.writehead ({"Content-type": "Text/plain"});

This is some unique-looking code. This are how Node retrives
Parameters passed in from client requests. The URL module
Handles all of 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'll create
Our random number is 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-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 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 ...");

Place the above code in a file called "Random.js". Now, to start the application and run it (and then create the 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 it looks like when the server is 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 for any connections, let's test it. Since we created a simple RESTful API, we can use our web browser to access this application. Type the following address (make sure you complete 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 to get another random number. That's it, that's your first Node application!

What is Node good for?

So far, you should be able to answer the question "What Node is," but you may not know when you should use it. This is an important question to ask because node is good for some things, but on the other hand, node may not be a good solution for other things at the moment. You need to be careful about when you use Node, because using it in the wrong circumstances can result in an extra coded LOT.

What is it good for?

As you've seen before, Node is ideal for situations where you expect high traffic, and server-side logic and processing needs are not necessarily significant before responding to the client. Typical examples of Node performance include:

1.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 does not require a lot of logic; it simply looks for some values from a database and combines 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 most busy company's API requirements.

2.Twitter queues

Imagine a company like Twitter that must receive tweets and write them to a database. In fact, there are almost thousands of tweets per second, and it is not possible for the database to handle the number of writes required during rush hours. 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 separate process can write them to the database. Node's role here is to quickly collect tweets and pass this information on to another process responsible for writing. Imagine another design-a regular PHP server itself trying to process writes to the database-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. 1 million tweets per second requires 500 servers. Instead, Node can handle each connection without blocking the channel, thus capturing as many tweets as possible. A Node machine that can handle 50,000 of tweets requires only 20 servers.

3. image File Server

A company with a large distributed web site, such as Facebook or Flickr, may decide to use all machines for service images only. Node will be a good solution to this problem because the company can use it to write a simple file retriever and then handle tens of thousands of connections. Node will look for the image file, return the file or a 404 error, and then do nothing. This setting will allow such distributed web sites to reduce the number of servers required for static files such as service images,. js, and. css files.

What's bad about it?

Of course, in some cases, Node is not an ideal choice. The following are areas where Node is not good at:

1. Dynamically created pages

Currently, Node does not provide a default method for creating dynamic pages. For example, when using JavaServer pages (JSP) technology, you can create a index.jsp page that contains loops in such a JSP code snippet. Node does not support such dynamic, HTML-driven pages. Also, Node is less suited for Web servers such as Apache and Tomcat. Therefore, if you want to provide such a server-side solution in Node, you must write your entire solution yourself. PHP programmers don't want to write a PHP converter for Apache every time they deploy a Web application, and that's what Node asks you to do so far.

2. Relational database heavy applications

Node is designed to be fast, asynchronous, and non-blocking. The database does not necessarily share these goals. They are synchronized and blocked, because calls to the database will block the channel until the result is generated. Therefore, a large number of database calls, a large number of reads, and a large number of written Web applications are very unsuitable for node for each request, because the relational database itself can offset the many advantages of node. (The new NoSQL database is better suited to Node, but that's completely another topic.) )

Conclusion

The question is, "What is Node.js?" should have been answered. After reading this article, you should be able to answer this question with a few clear and concise sentences. If so, you have come to the fore of many coders and programmers. I've talked to a lot of people about node, but they've been confused about what node is. Understandably, they have the Apache way of thinking-the server is an application that puts HTML files in it and everything works. And Node is the purpose-driven. It is a software program that uses JavaScript to allow programmers to quickly and easily create fast, scalable Web servers. Apache is ready to run, and Node is code ready.

Node completes its goal of providing a highly scalable server. Instead of allocating one thread per connection model, it uses a "each connection one process" model, creating only the memory needed for each connection. 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 Node's ideal goal-writing a highly scalable solution becomes easier.

As important as understanding Node is, understanding what it is not. Node is not an alternative to Apache, which is designed to make PHP Web applications easier to scale. This is true indeed. In this initial phase of Node, a large number of programmers are unlikely to use it, but in a scenario where it works, it behaves very well.

What should you expect from Node in the future? This is perhaps the most important issue that arises from this article. Now that you know what it's doing, you should wonder what it's going to do next. Over the next year, I expect Node to provide better integration with existing Third-party support libraries. Now, many third-party programmers have developed Plug-ins for Node, including adding file server support and MySQL support. You want Node to start integrating them into its core functionality. Finally, I also want Node to support some kind of dynamic page module so that you can perform operations in HTML files in PHP and JSP (perhaps an NSP, a Node server page). Finally, hopefully one day there will be a "deployed" Node server that can be downloaded and installed, just put your HTML files into it, just like you would with Apache or Tomcat. Node is still in its infancy, but it is developing very quickly and may soon be in your sights.

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.