Home >Web Front-end >JS Tutorial >What exactly is Node.js? What are the benefits of Node.js? _node.js
Node is a server-side JavaScript interpreter that will change the concept of how servers should work. Its goal is to help programmers build highly scalable applications and write code that can handle tens of thousands of simultaneous connections to one (and only one) physical machine.
Introduction
If you've heard of Node, or read some articles proclaiming how awesome Node is, you might be wondering, "What the hell is Node?" Even after looking at Node's homepage, you might even Still don’t understand what Node is? Node is certainly not for every programmer, but it may be something that some programmers have been struggling with.
In an attempt to explain what Node.js is, this article will briefly provide some background information: the problem it solves, how it works, how to run a simple application, and finally, when 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 if you should continue learning Node so you can use it for your business.
What problem is Node designed to solve?
Node’s stated goal is to “aim to provide a simple way to build scalable network programs.” What's wrong with the current server program? Let's do a math problem. In languages like Java™ and PHP, each connection spawns a new thread, and each new thread may require 2 MB of accompanying 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. Of course, this will increase costs such as server costs, traffic costs, and labor costs. In addition to these rising costs, there is also the potential technical issue that users may use a different server for each request, so any shared resources must be shared across 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 handle.
Node's solution to this problem is to change the way it connects to the server. Instead of spawning a new OS thread for each connection (and allocating some accompanying memory for it), each connection emits an event that runs in a process of the Node engine. Node claims that it can never deadlock because it doesn't allow locks at all and it doesn't block I/O calls directly. Node also claims that the servers it runs on 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? It would be scary if you had a web application that needed to handle so many connections! That's a "if you have this problem, it's not a problem at all" kind of problem. Before answering the question above, let’s take a look at how Node works and how it’s designed to operate.
Node is definitely not what?
Yes, Node is a server program. However, the base Node product is certainly not like Apache or Tomcat. Essentially, those servers are "ready to install" server products, allowing applications to be deployed immediately. With these products, you can have a server up and running in under a minute. Node is certainly not this product. Similar to Apache, which allows developers to create dynamic web pages by adding a PHP module and an SSL module to implement secure connections, Node also has a module concept that allows modules to be added to the Node core. There are literally hundreds of modules to choose from 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 part of Node will be discussed later in this article.
How does Node work?
Node itself runs V8 JavaScript. Wait, JavaScript on the server? Yes, you read that right. Server-side JavaScript may be a new concept to programmers who only use JavaScript on the client, but the concept itself is not far-fetched, so why can't the same programming language used on the client be used on the server?
What is a V8? The V8 JavaScript engine is the underlying JavaScript engine used by Google for its Chrome browser. Few people consider what JavaScript actually does on the client machine? In fact, the JavaScript engine is responsible for interpreting and executing the code. Using V8, Google created a super-fast interpreter written in C that 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 one browser. So Node actually takes the V8 JavaScript engine written by Google and rebuilds it to work on the server. It's perfect! Why create a new language when a good solution is already available?
Event-driven programming
Many programmers have been educated to believe 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
// 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");
});
Actually, there is no difference between server side and client side. Yes, there's no button clicking or typing into the text field, but at a higher level, events are happening. A connection is established, this is an event! Data is received through the connection, which is also an event! Data stops flowing through the connection, this is still an event!
Why is this type of setup ideal for Node? JavaScript is a great event-driven programming language because it allows the use of anonymous functions and closures, and more importantly, its syntax is familiar to anyone who has written code. The callback function that is called when an event occurs can be written at the point where the event is captured. This makes the code easy to write and maintain, with no complex object-oriented frameworks, no interfaces, and no possibility of over-engineering. Just listen to the event, write a callback function, and let the system handle everything else!
Sample Node Application
Finally, let’s look at some code! Let's put everything we've discussed together to create our first Node application. We already know that Node is ideal for handling high-traffic applications, so we'll create a very simple web application, one built for maximum speed. Here are the specific requirements from the “boss” for our sample application: Create a random number generator RESTful API. This application should accept one input: a parameter named "number". The application then returns a random number between 0 and this parameter and returns the resulting number to the caller. Since the "boss" wants the application to become a widely 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 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 correctly
console.log("Random Number Generator Running...");
启动应用程序
将上面的代码放入一个名为 “random.js” 的文件中。现在,要启动这个应用程序并运行它(以便创建 HTTP 服务器并监听端口 80 上的连接),只需在您的命令提示中输入以下命令:% node random.js。下面是服务器已经启动并运行时看起来的样子:
Access the App
The application is up and running. Node is listening for all connections, let's test it. Since we created a simple RESTful API, the application can be accessed using a web browser. 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, your first Node application!
What is Node good for?
At this point, you may be able to answer the question "What is Node", but you may also have another question: "What is Node used for?" This is an important question to ask because there is definitely something that could benefit. on Node.
What is it good for?
As you saw earlier, Node is great for situations where you anticipate potentially high traffic, but not necessarily a lot of server-side logic and processing required before responding to the client. Typical examples of Node excelling include:
RESTful API
A web service that provides a RESTful API receives several parameters, parses them, assembles a response, and returns a response (usually less text) to the user. This is an ideal situation for Node because you can build it to handle tens of thousands of connections. It still doesn't require a lot of logic; it essentially just looks up some values from some database and composes them into a response. Since responses are small amounts of text and inbound requests are small amounts of text, the traffic is not high and a single machine can handle the API needs of even the busiest companies.
Twitter Queue
Imagine a company like Twitter that has to receive tweets and write them into a database. In reality, with almost thousands of tweets arriving per second, it is impossible for the database to handle 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 handle tens of thousands of inbound tweets. It quickly and easily writes them to an in-memory queuing mechanism (such as memcached), from where a separate process can write them to the database. Node's role here is to quickly collect tweets and pass this information to another process responsible for writing. Imagine an alternative design (where a regular PHP server would try to handle writes to the database itself): each tweet would cause a short delay in being written to the database because the database call is blocking the channel. A machine designed this way might only be able to handle 2000 inbound tweets per second due to database latency. Processing 1 million tweets per second would require 500 servers. Instead, Node handles 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’ve played the game Call of Duty online, you’ll immediately realize something when you look at the game’s statistics: To generate that level of statistics, you have to track a huge amount of information. In this way, if there are millions of players playing online at the same time, and they are in different positions in the game, a huge amount of information can be generated very quickly. Node is a great solution for this scenario because it ingests the data generated by the game, performs minimal merging of the data, and then queues the data so that it can be written to the database. Using an entire server to track how many bullets a player fires in a game seems silly, and if you use a server like Apache there may be some useful limitations; but conversely, if you use a dedicated server to track all statistics for a game Data, as you would do with a server running Node, that seems like a smart move.
Node module
Although not the original topic of this article, this article has been expanded to include an introduction to Node Modules and Node Package Manager due to popular readership. Just like developers accustomed to using Apache, you can also extend Node's functionality by installing modules. However, the modules available for Node greatly enhance the product, and those modules are so useful that developers who will use Node will usually install several of them. Therefore, modules are becoming more and more important, and even become a key part of the entire product.
In the "References" section, I've provided a link to the modules page, which lists all available modules. To demonstrate the possibilities that modules can offer, I have included the following modules among the dozens available: one for writing dynamically created pages (such as PHP), one to simplify the use of MySQL, and one to help use WebSockets , and a module to assist with text and parameter parsing. I won’t go into detail about these modules because this overview article is intended to help you understand Node and determine if you need to learn more in depth (again), and if you do, then you will definitely have the opportunity to use the available modules.
Also, a feature of Node is the Node Package Module, which is a built-in feature for installing and managing Node modules. It handles dependencies automatically, so you can be sure: any module you want to install will be installed correctly and include the necessary dependencies. It also supports publishing your own modules to the Node community, should you choose to join the community and write your own modules. You can think of NPM as a method that allows you to easily extend the functionality of Node without worrying about breaking your Node installation. Likewise, if you choose to dive into Node, NPM will be an important part of your Node solution.
Conclusion
After reading this article, the question you had at the beginning of this article "What exactly is Node.js?" should have been answered, and you should be able to answer this question in a few clear and concise sentences. If so, you're already ahead of many programmers. I've talked to a lot of people about Node, but they've always been confused about what Node is actually used for. Understandably, they have an Apache way of thinking, where the server is an application, you put an HTML file in it and everything works. Since most programmers are familiar with Apache and its uses, the easiest way to describe Node is to compare it to Apache. Node is a program that can do everything Apache can do (with the help of a few modules), and much more as an extensible JavaScript platform that you can build on.
As you can see from this article, Node accomplishes its goal of providing a highly scalable server. It uses a very fast JavaScript engine from Google, 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 making it easier to write a highly scalable solution.
Just as important as understanding what Node is, is understanding what it is not. Node is not just a replacement for Apache, it is designed to make PHP web applications easier to scale. Nothing could be further from the truth. Even though Node is still in its infancy, it's growing very quickly, community participation is so high, and community members have created so many great modules that within a year, this evolving product could be in your business.