Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Node.js?

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about what is Node.js. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Node is not a panacea! But it does solve some key problems.

Learning Node is not an easy task, but the reward you receive is worth your efforts. Because at present, only JavaScript can solve many difficult problems in Web application development.

"are you cool? come and use me!" Node.js provides a series of cool API and toolkits for the latest programming languages, which can be directly applied to traditional Rails, Ajax, Hadoop, and even, to some extent, iPhone development and HTML5. If you have attended some large technical conferences, you will always hear keynote speeches about Node.js, although these topics are still a bit out of reach for the average developer.

You may have heard that Node.js (sometimes we call it "Node" for short) is a server-side solution that runs JavaScript and can handle HTTP requests as a Web service. If these things don't confuse you, the discussion of ports, sockets and threads will become the hottest topic of the moment, and you will find these things dazzling you. Does this really fall into the category of JavaScript? Why do so many people around the world prefer to run JavaScript off the browser, let alone run JavaScript on the server side?

The good news is that everything you hear (and think of) about Node is true. Node really belongs to the category of network programming, which is used to handle server-side requests and responses. The bad news is that, like previous Rails, Ajax, and Hadoop, there are too few really practical technical materials. When the "excellent" framework based on Node matures, the technical materials will certainly keep up, but why wait for technical books and tutorials to come out before trying to use Node? Using Node now may bring unexpected changes to your code and even make your program easier to implement.

Warning from experts!

Like most technologies, Node is a new bottle of old wine: it looks opaque and weird, but it is only popular with small development teams. If you haven't been exposed to Node, you need to learn some server-side scripts that are easy to use. You need time to figure out Node, because even JavaScript running on the server side is very different from the client-side JavaScript. The reality is that you have to brainwash yourself in order to relearn the event handling mechanisms around JavaScript, asynchronous IO, and some network basics.

Unfortunately, this means that if you have been developing with Node for more than two years, you will find this article monotonous and too simple. You will start looking for new "stimuli", such as running Node on the client, or start experimenting with event IPUBO, reflector mode, and npm. You will find that the world of Node is so interesting that many advanced Node technologies have a certain epic beauty that is still out of reach for beginners. So maybe you should share your knowledge with your peers, especially those who don't know Node, and teach them advanced Node technology when they start to be interested in Node.

Node: a few small examples

First of all, you should realize that Node is used to run stand-alone JavaScript programs, not in some HTML snippet in your browser. It is a real file stored in the file system, executed by the Node program, runs in a daemon mode, and opens listening to certain ports.

Skip hello world

The most classic example is, of course, "Hello World", which has source code on Node's official website (http://nodejs.org/docs/latest). Almost everyone comes into contact with Node from Hello World. Now let's skip the simplest example and look at some more interesting examples: implementing a program that can send files from the server to the client (instead of just sending a piece of text to the client).

Var sys = require ("sys"), http = require ("http"), url = require ("url"), path = require ("path"), fs = require ("fs"); http.createServer (function (request, response) {var uri = url.parse (request.url) .pathname; var filename = path.join (process.cwd (), uri) Path.exists (filename, function (exists) {if (! exists) {response.writeHead (404, {"Content-Type": "text/plain"}); response.end ("404 Not Found\ n"); return } fs.readFile (filename, "binary", function (err, file) {if (err) {response.writeHead (500,{ "Content-Type": "text/plain"}); response.end (err + "\ n"); return;} response.writeHead Response.end (file, "binary");}) .console.log ("Server running at http://localhost:8080/");")

Thanks to Mike Amundsen, he gave a similar implementation of this code. This example is a piece of code submitted by Devon Govett on Nettuts+. Although it has been updated according to the new version of Node, Devon's entire post is a very good introductory textbook, especially for beginners.

If you are a novice, you can save the above code to a text file and name it NodeFileServer.js. You need a Node runtime before running, and the latest Node version can download this file from the official website or remove the source code from github. You need to compile the source code. If you have not used Unix and are not familiar with make and configure, you need to consult the online compilation manual for help.

Node is not JavaScript,Node and can run JavaScript

You just saved NodeFileServer.js as a file, don't worry, we'll run it back later. Now, let's move to reality and execute typical configuration and compilation commands in Unix:

. / configure make make install

This confirms the fact that Node is not JavaScript,Node is a program that can run JavaScript, but Node is definitely not JavaScript. In fact, Node is a program based on C. You can view the files in the Node/src directory through ls, and you can see the source code of Node:

Most people will think that JavaScript is a bad language, let alone use it to implement server-side functions, but you are only half right. Yes, JavaScript may not be competent for operating system-level Socket and network programming. But Node is not implemented by JavaScript, it is based on C #. C language is perfectly competent for network programming of any order of magnitude. On the other hand, JavaScript is fully capable of passing instructions to C programs, which then control the operating system "dungeons". In fact, JavaScript is more accessible to developers than C, which is noteworthy, and this reason will be mentioned again and again if you want to do some serious programming with Node.

The basic usage of Node further reflects how Node works with JavaScript, and Node is not JavaScript. You can run it from the command line:

-(bdm0509@Bretts-MacBook-Pro Sun, 29 May 11)-(/ Users/bdm0509/tmp/Node/src)-- (09:09 $)-> export PATH=$HOME/local/Node/bin:$PATH-(bdm0509@Bretts-MacBook-Pro Sun) 29 May 11)-(/ Users/bdm0509/tmp/Node/src)-- (09:09 $)-> cd ~ / examples-(bdm0509@Bretts-MacBook-Pro Sun 29 May 11)-(/ Users/bdm0509/examples)-- (09:09 $)-> Node NodeFileServer.js Server running at http://127.0.0.1:1337/

Now you must have a general idea of Node. There are indeed many points of knowledge that need to be further explained on this command line, such as what happened on port 1337. But all you need to know here is that Node is just a program that allows you to run JavaScript. Readers don't have to worry about how Node works with JavaScript, and I won't say much about it here, as long as I know that Node can run JavaScript. And you only need to learn the programming language JavaScript, so you don't have to worry about not knowing C. Keep in mind that this is the most important thing, you don't need to know C to write programs that Node can run.

Interaction with Node server

We just ran NodeFileServer.js on Node. At this point, you can access port 1337 of your computer and you can see the normal output.

Yes, the output is not surprising. But we should be aware that we have implemented a file server in just 20 lines of code. The output is the text of the script source file you just saved, not in binary form. This file server can output any file on it. If you put an image in the same directory, write the image file name in the URL suffix, like this: http://localhost:8080/my_image.png.

Node can also display binary image files. When you look back at this short program, you must think it's incredible. Isn't it comfortable that you can easily write a service program that you want with JavaScript? Not only that, but suppose you want to write a service that can handle multiple requests (this is a hint and open four, five or even ten browsers to access the server at the same time), which is easy to do. The fascinating thing about Node is that you can use a very simple and humble JavaScript program to achieve the results you want.

Quick start manual

Topics around Node are always worth taking some time to discuss than code that runs purely on the server side. Anyway, let's start with a piece of code, take an overview of the NodeFileServer.js file, and look at the code:

Var http = require ('http'); http.createServer (function (req, res) {res.writeHead (200,{' Content-Type': 'text/plain'}); res.end (' Hello World\ n');}) .birthday (1337, "127.0.0.1"); console.log ('Server running at http://127.0.0.1:1337/');

The function require () is called first, and require () is one of the most commonly used functions for programmers. In fact, this function is also mentioned in the CommonJS specification, when discussing the concept of the JavaScript module, and in a cool implementation of Davd Flanagan in 2009. In other words, require () may be new to you, but it's not a function that Node adds at random, it's the core concept of modular programming with JavaScript, and Node makes the most of this feature.

Next the http variable is used to create a server. This service uses a callback function to handle the action when a connection is generated. The callback function here does not modify the request too much, but simply outputs a string "Hello World" in text/plain format as the request response. The logic is very simple.

In fact, the standard mode for using Node is shown here:

Define the interaction type and get a variable to handle the interaction (via require ()).

Create a new service (via createServer ()).

Bind a callback to the service to process the request. The function that includes handling the request should include a request. And a response

Notify the server to start the service, where you need to specify the IP and port (via listen).

The confusion of the interpreter

Although this approach makes it easy to implement a service using JavaScript (regardless of whether the virtual machine running the code is actually running a C program or whatever), it begs the question: do you need to write a server using JavaScript? To find the answer to this question, let's consider a very typical scenario.

The treatment of JSON

This is a very typical web application. The foreground uses HTML and CSS,JavaScript for data verification and data exchange with the background. Because you are at the top of the web interaction, you use Ajax to submit data to the background and get it from the background, rather than relying solely on form submission. If you do this, you will also like to use JSON very much. JSON is the most popular format for transmitting data today.

Therefore, the Ajax can also be likened to "sending me some guitar information from an online auction site." This request goes over the network to a server running the PHP program. The PHP server has to return a lot of information to JavaScript, and the information must be sent to the client in some form of packet, and the packet can be parsed by JavaScript. So the data can be packaged into an array and converted to JSON, like this:

$itemGuitar = array ('id' = >' itemGuitar', 'description' = >' Pete Townshend once played this guitar while his own axe'. Was in the shop having bits of drumkit removed from it.', 'price' = > 5695.99,' urls' = > array ('http://www.thewho.com',' http://en.wikipedia.com/wiki/Pete_Townshend')); $output = json_encode ($itemGuitar); print ($output)

Back on the client side, JavaScript gets the returned packet, which is programmed in JSON format due to the conversion. It's like this:

{"id": "itemGuitar", "description": "Pete Townshend once played this guitar...", "price": 5695.99, "urls": ["http://www.thewho.com"," http://en.wikipedia.com/wiki/Pete_Townshend"]}

This transformation is standard and is equivalent to each other before and after the conversion. Next, you can convert the string to a JavaScript object, and you can call eval (), like this:

Var itemDetails = eval ('('+ jsonDataString +')')

The result is a normal JavaScript object whose properties are consistent with the data structure of the JSON array. Of course, since the jsonDataString is usually returned by the server, you usually need to parse the returned result like this:

Var itemDetails = eval ('('+ request.responseText +')')

This is the most typical JSON processing, but there is a very serious problem.

Subtle destructiveness to physical code

(translation note: this subtitle is really puzzling. The author explains in a roundabout way that one of the advantages of Node is that both the front end and the back end use the same language JavaScript, which is barrier-free for JSON parsing, while the current end uses JavaScript for JSON encoding and the background uses PHP for JSON decoding, which will bring some compatibility problems due to the different implementation of JSON parsing in multiple languages.)

First, one of the main problems with this type of code is that it is heavily dependent on the interpreter. In the previous example, the interpreter refers to the built-in JSON parser or code that implements parsing JSON, which actually depends on two things: the Java-based JSON parser, which is the same as eval () parsing the response text, and the PHP-based JSON parser. The JSON parser is already included in PHP5.2.0, but it is given in the form of external dependencies, not built into the kernel of PHP.

But this is not all the trumpeting of interpreters. After all, there are still many problems with the interpreter itself, such as parsing "I" into "I" and interpreting element 1 in the array into 2. Of course, there will be a large number of tests before the official release of the JSON tool to ensure that there are no errors in a variety of complex scenarios, including that the parsing results on the client side are exactly the same as those on the server side. In any case, this requires a lot of testing.

In any case, there are still many practical problems with JSON.

The choice of JSON parsers based on a language (JavaScript or PHP) is a big problem. In other words, the problem is not "translation" but "translator" (translation note: the author means that there is nothing wrong with the rules of JSON itself, but that the quality of JSON implementations in various languages varies, even with many bug.) When the version of a language is stable, the use and promotion of JSON parsers based on that language will be faster. As a result, JSON parsers have become so powerful that they can parse arbitrarily complex data structures, even if they are not actually used. Conversely, in each iteration (calculating the combination of paths and data types for each iteration), it is also possible to have data structures (or deep JSON paths) that cannot be parsed by the JSON interpreter.

The following figure shows the optional JSON interpreter

This is not to say that JSON itself is bad. In fact, we think that the popularity of JSON is due to its application in new areas. For new areas, we can't help but ask, "does this new thing support JSON?" Therefore, JSON needs to be constantly evolved, constantly tested, and constantly compatible with new platforms. As a programmer, you may need to reorganize your data structure, or wait for a new version to appear to meet your needs, or simply hack JSON. And these are what we call the waste of programming resources.

Suppose you can do plenty of food and clothing yourself to implement an interpreter, even so, you don't get a bargain by taking a shortcut, you just repeat the wheel with JavaScript.

Node avoids such problems, and the text you just read-- about PHP5.2.0 with embedded JSON, about converting objects into arrays, about the way data is organized using a new structure, about the implementation of new features in JSON-- will no longer exist in Node, because the front end uses JavaScript for JSON encoding and the background uses JavaScript for JSON decoding, and there will never be a problem.

The potential danger of eval () in JavaScript

Just as we don't have to treat Node as a new language, executing a piece of code through eval () in Node is the same as eval () in JavaScript (not recommended). It is well known that eval () is very dangerous. The code logic used by eval () to execute a piece of text can be understood as "typing SQL code directly into the text box to execute the query", which is not safe, which is actually malicious SQL injection. Every time eval () executes a string, a puppy in the Midwest shivers, and a mother on the eastern beach gets her toe stabbed and cursed. Eval () is very dangerous. There is a lot of information about this on the Internet, so I won't repeat it here. You can query "eval JavaScript evil" or "eval JavaScript injection" with google for more information.

Of course, eval () is also allowed in Node if there are no other contextual constraints, so the pitfalls of eval () still exist in Node. After all, the purpose of Node is not to completely solve the problem of eval (). Node is called event-based JavaScript or event-based Imax O. event-based is a very important concept in Node. But to thoroughly understand what event-based is and why it allows you to avoid the dangers of eval (), you need to understand how JSON works in applications, as well as the unique data structures that are adapted to the typical architecture of web applications.

Event-based Web application

Traditional Web form submission is a typical event-based pattern. In other words, a lot of data is entered in the Web form (user input text box, click the check box, select certain items from the list, and so on), and then the data is submitted to the server. This scenario is actually a single program event: the form data is submitted using POST. This is how Ajax-based Web applications work.

Send a large amount of data at once

For Ajax, it has something to do with event-based programming. Some interactions between the client and the server can be considered event-based. A typical scenario is to enter a provincial code and send a request to the server to get the name of the city and province. Here, Ajax through XmlHttpRequest does not require a lot of data to be thrown to the server at once. But this doesn't change the fact that most web applications are based on page refresh. Ajax has been more widely used in a lot of interesting visual-related interactions, rapid form validation, no refresh of submitted data, so as to avoid reloading the page. So, although you don't initiate a real POST request by submitting the form, you can simulate an POST form submission through Ajax.

Frankly speaking, this traditional way of Ajax interaction also hinders the innovation of Ajax programmers. Every time a request is sent (no matter how small the requested data), it will walk back and forth through the network. The server must respond to this request, usually by opening a new process. Therefore, if you are really developing in an event model environment, you may need to maintain the connection between your page and the server by issuing 10 to 15 separate small requests. The server will also create 10 to 15 threads for it (maybe less, depending on the server's policy of allocating thread pools when processing new requests). When this number is multiplied by 1000 or 10000 or 1000000, there will be problems such as memory overflows, conflicts caused by logical interlacing, network outages, and system crashes.

As a result, in most scenarios, Web applications need to maintain minimal dependence on events. One compromise is that the response of the server-side program returns not a small piece of data, but a packet with more redundant data structures, usually JSON data, and then encounters the problem of eval (). The problem is, of course, with eval (), but it is also inextricably linked to Web itself and server thread control, including HTTP request and response strategies between pages and servers, at least in this scenario.

Some people may not agree with the problems mentioned above, because you know that there are many ways to avoid the problems caused by direct eval (), and you will use things such as JSON.parse () instead of eval (). There are also many compelling arguments that encourage us to use eval () carefully. These things are worthy of further discussion. Anyway, if you take a look at too many problems like Stack Overflow caused by eval (), you will find that most programmers do not use eval () correctly or safely. This is really a problem. Because too many rookie programmers don't seem to realize how serious the problem with eval () is.

Constantly send a small amount of data

Node brings a new idea of architectural application. We can use event model to construct Web application based on Node, or "small" event model. In other words, you should send a large number of requests based on a large number of events, each with a small packet, or grab a small amount of data from the background as needed, rather than sending a small number of requests, each with a large amount of data. In many scenarios, in most cases you need to wake up the GUI program (the Java Swing programmer's GUI knowledge reserve can come in handy). Therefore, when the user enters the last name and first name and moves to the next input box, a request has been made to verify that the entered user name already exists. The same is true for the verification of provincial and municipal codes, addresses and phone numbers. Each time that occurs on the page, a request and response are generated.

What's the difference? Why can Node do this and avoid existing threading problems? In fact, Node is not so mysterious, and the Node website fully explains its philosophy:

The goal of Node is to provide a solution for building scalable web applications. In the hello world example, the server can handle many client connections at the same time. Node has an agreement with the operating system that if a new link is created, the operating system will notify Node and then go to sleep. If someone creates a new link, it (Node) performs a callback, each of which takes up very little stack overhead.

Node is non-blocking, and there are no competing threads of the same origin (Node is very happy to handle immediate requests, so let it happen), and when a new request arrives at the server, you don't have to do anything alone for that request. Node just sits there leisurely and waits for the request to happen, and processes the request if there is a request. It can be implemented with very simple code without spending the programmer's precious energy to implement a complete set of server-side logic.

Yes, chaos is inevitable.

It is worth mentioning that the problems caused by non-blocking systems also occur in this programming mode: a process (non-thread) waits for a data storage operation, and then another operation to grab unrelated data occurs. This unexpected operation will affect the existing waiting. That is, the operation itself is not atomic. Note, however, that most event-based web programming patterns are "read-only"! You've probably never had a "micro-request" to modify data, or it's very rare. On the contrary, it is very common to use such requests to verify the legitimacy of data and query data. In this case, it is best to respond directly to the request. The database itself will do the locking operation, generally speaking, an excellent database can efficiently lock and unlock the data operation without the server-side program code to do more. On the other hand, Node is more efficient than the operating system in maintaining and releasing threads, so that the server does not have to open up a separate process for "web response".

In addition, Node also plans to implement "process branches" (process forking), and HTML5 Web Workers API provides engine (specification) support for more complex process control. Similarly, if you use an event-based model to build web applications, your program may have at least 100 scenarios that require thread support. Eventually you will find that your programming ideas and the way you think about problems have changed, and your focus will be on the logic of server-side processing of requests, rather than on how Node works.

The opportunity for Node to display his talents

It doesn't matter if we talk about another web development model, whether it's Node or event-based programming, because it's so important. In short: suit the remedy to the case! In a nutshell, different solutions are adopted for different problems, regardless of whether this solution solves other problems or not.

Thinking set

There is a certain mindset not only in the field of web design, but also in all programming. This mindset can be described as follows: the more you learn and master, the more problems you can solve and the more application scenarios of your skills. This seems to be taken for granted, unless you delve deeper into the technology. Yes, it's not always a bad thing to learn new languages and new tools and use them widely. But there is often a misunderstanding, that is, because you know it, you use it, not because the skills and tools you have are "best suited" for your business.

Let's take a look at Ajax. There has been too much discussion about Ajax. We know that Ajax provides a reliable solution for quick query requests without refresh. Now because of the abuse of Ajax, it is too much to replace the traditional form submission. We encounter a new technology, learn it, master it, apply it, and then "abuse it". After all, many business scenarios only require traditional form submission, not Ajax. It's simple to say, in fact, there are thousands of cases of abuse of Ajax, simply because of the blind respect for Ajax by the development engineer of an application.

Similarly, Node faces such a problem. When you first meet Node and find its benefits, you want to use it everywhere. You will replace PHP or Perl programs with Node in a hurry. How did it turn out? It sucks. In fact, you are already suffering from obsessive-compulsive disorder, and you always want to use Node in scenarios that go against its original intention: use JavaScript to submit a large amount of data to Node, or return a large amount of JSON data to JavaScript through Node and give it to the front end for eval (), or simply use Node as a file server to return HTML pages or do HTTP redirection.

But none of these scenarios is what Node is good at. Node is better at handling small requests and event-based IHTML O, using Node to solve the rapid communication between client and server, using form submission to send large amounts of data to the server, using PHP and Perl to handle heavy database operations and dynamic HTML page generation. Use Node to run on the server side to handle small requests. Whether it's using Rails or Spring and a variety of server containers, just ask for it on demand. Be sure to understand what the problem you need to solve, and take the best solution based on it, rather than based on the skills you have right now.

The simple original intention of Node

One last thing to note is that as you get deeper and deeper into your programming, you'll find that you don't have to be proficient in every tool, API, and framework you use. Use the knife on the blade, not the hammer as a drill bit. Understand the scenarios in which each tool applies and the problems that can be solved, and then find the most appropriate application scenario for the tool. If you want to become a superhuman generalist (programmers often want to know everything), you are getting farther and farther away from the "expert", which means to be very proficient in one or two aspects. Of course, every boss wants to find superhuman generalists, but such people are often impossible to find.

Learning Node may be difficult, but it's well worth it. Why? Because you are looking for a solution for web applications based on JavaScript. This means that you won't lose your existing JavaScript programming skills, and when you need to use PHP or Perl, you have to relearn a new language, and Node doesn't have to fight so hard. The problems of learning new languages are much greater than the benefits of learning them.

The challenge in learning Node is that you need to think more actively, break programs into small, low-coupling pieces, and then assemble them like arrays. However, Node and event-based iAccord O can not solve all the problems, but it is certain that many key problems can only be solved by Node.

The above is what the editor shares with you what is Node.js, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report