What is node. js? Node.js details

  • 2020-03-30 03:08:44
  • OfStack

Introduction to the

If you've ever heard of Node, or read articles about how great it is, you might be thinking, "what the hell is a Node?" While not for everyone, Node may be the right choice for some.

In an attempt to explain what node.js is, this article explores the problems it can solve, how it works, how to run a simple application, and finally, when Node is and is not a good solution. This article does not cover how to write a complex Node application, nor is it a comprehensive tutorial on Node. Reading this article should help you decide whether you should learn Node so you can use it for your business.

What problems does Node aim to solve?

Now that you have a program that can handle tens of thousands of concurrent connections, what can you actually build with Node? If you had a web application that had to deal with that many connections, it would be "scary"! It's a "if you have this problem, it's not a problem at all" question. Before answering the above question, let's take a look at how Node works and how it is designed to work.

Node is definitely not what

Yes, Node is a server program. However, it is certainly not like Apache or Tomcat. Those servers are standalone server products that can be installed and deployed immediately. With these products, you can get a server up and running in a minute. Node is definitely not that kind of product. Apache can add a PHP module to allow developers to create dynamic web pages, and programmers using Tomcat can deploy JSPs to create dynamic web pages. Node is definitely not of this type.

In its early stages (currently version 0.4.6), Node is not yet a "run-ready" server program that you can install, put files into, and have a fully functional web server. Even getting the web server up and running after installation is complete requires a lot of work.

How Node works

Node itself runs V8 JavaScript. Wait, JavaScript on the server? Yes, you read that right. Server-side JavaScript is a relatively new concept that was mentioned about two years ago during a discussion of the Aptana Jaxer product on developerWorks (see resources). Although Jaxer never really caught on, the idea itself isn't far-fetched -- why not use the programming language used on the client on the server?

What makes V8? The V8 JavaScript engine is the underlying JavaScript engine that Google USES for their 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. With V8, Google created an ultra-fast interpreter written in C++ with another unique feature. You can download the engine and embed it in any application. It is not limited to running in a browser. So Node actually USES a V8 JavaScript engine written by Google and reconstructs it to be used on the server. Perfect! Why create a new language when a good solution is already available?

Event-driven programming

Many programmers are educated to think that object-oriented programming is the perfect programming design, and to dismiss other programming methods. Node USES a so-called event-driven programming model.

Listing 1. Event-driven programming using jQuery on the client side


// 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 side. Yes, there are no button clicks, no typing into the text field, but at a higher level, events are happening. A connection is made - event! Data is received over a connection - event! Data stops through the connection - 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, its syntax is familiar to anyone who has written code. The callback function called when an event occurs can be written at the capture event. This way, the code is easy to write and maintain, with no complex object-oriented frameworks, no interfaces, and no potential to build anything on top of it. Just listen for the event, write a callback, and event-driven programming takes care of everything!


Sample Node application

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 languages
var 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 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 (thereby creating the HTTP server and listening for connections on port 80), simply type the following command at your command prompt: % node random.js. Here's what it looks like when the server is up and running:


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

Access application

The application is up and running. Node is listening for any connection, so let's test it out. Since we created a simple RESTful API, we can use our web browser to access the application. Type the following address (make sure you complete the above steps) : http://localhost/? Number = 27.

Your browser window will change to a random number between 0 and 27. Click the reload button on your browser to get another random number. That's it, this is your first Node application!

What is Node good for?

At this point, you should be able to answer the question "what is Node?" but you may not know when to use it. This is an important question to ask, because Node is good for some things, but conversely, Node may not be a good solution for others right now. You need to be careful when you decide to use Node, because using it in the wrong case can result in a LOT of extra code.

What is it good for?

As you've seen before, Node is perfect for situations where you can expect high traffic, and where the server-side logic and processing requirements are not necessarily huge before responding to the client. Typical examples of Node's superior performance include:

1. The RESTful API

A web service that provides a RESTful API takes several parameters, parses them, composes a response, and returns a response (usually less text) to the user. This is the ideal situation for Node, because you can build it to handle tens of thousands of connections. It doesn't require a lot of logic; It just looks up some values from a database and combines a response. Since the response is a small amount of text, and the inbound request has a small amount of text, traffic is not high, and a machine can handle the API requirements of even the busiest companies.

2. Twitter queue

Imagine a company like Twitter, which has to take tweets and write them into a database. In fact, with nearly thousands of tweets arriving every second, it is impossible for the database to keep up with the number of writes needed during peak hours. 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 can quickly and easily write them to an in-memory queuing mechanism (such as memcached) from which 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 another design -- a regular PHP server trying to handle writes to the database itself -- where each tweet causes a short delay in writing to the database because the database call is blocking the channel. Because of database delays, a machine of this design might be able to handle only 2,000 inbound tweets per second. A million tweets per second requires 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.

3. Image file server

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

What is it bad for?

Of course, in some cases, Node is not an ideal choice. Here's where Node isn't good:

1. Dynamically created pages

2. Relational database heavy applications

The purpose of Node is to be fast, asynchronous, and non-blocking. The database does not necessarily share these goals. They are synchronous and blocked, because calls to the database during read and write will block the channel until the result is generated. Therefore, a web application that requires a lot of database calls, a lot of reading, and a lot of writing per request is a poor fit for Node, because the relational database itself offsets many of the benefits of Node. (the new NoSQL database is more suitable for Node, but that's a completely different topic.)

conclusion

The question is "what is node. js?" I think we have the answer. After reading this article, you should be able to answer this question in a few clear and concise sentences. If so, you are ahead of many coders and programmers. I've talked to a lot of people about Node, but they've always been confused about what it is. What they have, understandably, is the Apache way of thinking - the server is an application, put an HTML file in it, and everything will work. Node is purpose driven. It is a software program that USES JavaScript to allow programmers to easily and quickly create fast, scalable web servers. Apache is ready to run, and Node is coded ready.

Node accomplishes its goal of providing a highly scalable server. Instead of assigning a "one thread per connection" model, it USES a "one process per connection" model to create only the memory needed for each connection. It USES one of Google's very fast JavaScript engines: V8. 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 -- it's easier to write a highly scalable solution.

Just as important as understanding what Node is is understanding what it is not. Node is not a replacement for Apache, which aims to make PHP web applications easier to scale. And so it is. At this early stage of Node, it is unlikely to be used by a large number of programmers, but it works well in scenarios where it works.

 


Related articles: