node, did you hear? The life of node and the applicable scene

Source: Internet
Author: User
Tags end eval file system sql new features string sql injection version

Article Introduction: What is node?

Translator Press: OReilly recently a booklet "What is Node?", a brief explanation of Node's life and the application of the scene, the author easy and smooth, full content, is very rare learning materials. Translate it out and share it with us ~

Full text:http://jayli.github.com/whatisnode/index.html
Author:Brett McLaughlin , Original:What is Node?

node is not a panacea! But it does solve some of the key issues.

Learning node is not an easy thing to do, but the rewards you receive are worthy of your pay. Because of the many problems in Web application development today, only JavaScript can be solved.

Directory

1, the Expert's warning!
2,node: A few small examples
3,node is not Javascript,node can run JavaScript
4, interacting with the node server
5. Quick Start Manual
6, the confusion of the interpreter
7, event-based Web applications
The 8,node

"Are you cool enough?" Come on, use me! "Node.js provides a cool array of APIs and toolkits for the most trendy programming languages that can be applied directly to traditional rails, Ajax, Hadoop, and even to some extent for iphone development and HTML5. If you've attended some big technical meetings, you'll always hear some keynote speeches about node.js, even though these topics are still difficult for ordinary developers.

You may have heard that node.js (sometimes referred to as "Node") is a server-side solution that can run JavaScript and can act as a Web service to handle HTTP requests. If these things don't make you dizzy, then the conversation about ports, sockets and threads becomes the hottest topic of the moment, and you'll feel dazzled by them. Do these things really belong to the JavaScript category? Why do so many people in the world prefer to run JavaScript out of the browser, not to mention running JavaScript on the server side?

The good news is that everything you hear (and think about) about node is right. Node is indeed part of network programming to handle server-side requests and responses. The bad news is that, like rails, Ajax, and Hadoop, there are really very few technical data available. When the "good" framework based on node matures, the technical data will certainly follow, but why wait until the technical books and tutorials come out and try to use node? Using node now will probably bring unexpected changes to your code and even make your program easier to implement.

Expert door Warning!

Like most technologies, node is also a new bottle of old wine: it looks opaque and bizarre, but it is favored by the small development team alone. If you don't have access to node, you'll need to learn some very easy server-side scripts. You need time to make sense of node, because even with JavaScript, which is running on the server side, it is very different from client JavaScript. The reality is that you have to brainwash yourself to learn to understand the event-handling mechanism around JavaScript, asynchronous IO, and some network basics.

Unfortunately, this means that if you've been using node for more than two years, you'll find this article tedious and simplistic. You will start looking for new "stimuli", such as running node on the client, or starting to try event I/O, reflector mode, and NPM. You will find that the world of node is so interesting that even a lot of node advanced technology has some kind of epic beauty that is still difficult for beginners. So maybe you should share your knowledge with your peers, especially those who don't know node, and share advanced technology with the node when they start to be interested in node.
Node: A few small examples

First, you should realize that node is used to run standalone JavaScript programs, rather than running in an HTML fragment in the browser. It is a real-life file stored in the file system, executed by the node program, running in a daemon mode, and opening the listener on some ports.

Skip Hello World

The most classic example of course is "Hello World", which has source code on the node website (http://nodejs.org/docs/latest). Almost everyone begins to touch node from Hello World. Now let's skip the simplest example and look at some of the more interesting examples: Implementing a program that can send files from the server to the client (rather than 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"); h
    Ttp.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 (5
                {"Content-type": "Text/plain"});
                Response.End (err + "\ n");
            Return
            } response.writehead (200);
        Response.End (file, "binary");
    });
});
}). Listen (8080); Console.log ("Server running at http://localhost:8080/"); 

Thanks to Mike Amundsen, he gave a similar implementation of the 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, but Devon's entire post is a very good introductory learning material, especially for beginners.

If you are a novice, you can save the above code in a text file named Nodefileserver.js. Before you run, you need a node to run the environment, the latest node version can download the file from the official website or from the GitHub source code down. You need to compile the source code, if you have not used Unix, not familiar with make and configure, you need to consult the online compilation manual to seek help.

node is not Javascript,node can run JavaScript

You just saved nodefileserver.js as a file, don't worry, we'll come back and run it. Now, let's go to the real world and perform typical configuration and compilation commands in Unix:

./configure make make
install

This makes us convinced of 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 written on C. You can view the files in the NODE/SRC directory through LS, and you can see the source of node:

Most people would assume that JavaScript is a bad language, not to mention using it to implement server-side functionality, but you're only half right. Yes, JavaScript may not be competent for operating system-level sockets and network programming. But node is not a JavaScript implementation, it is based on C implementation. C language can be perfect for any degree of network programming. JavaScript is fully capable of passing instructions to the C program, and then the C program to manipulate the operating system "dungeon". In fact, JavaScript is more likely to be accessible to developers than C, which is noteworthy, and is mentioned repeatedly 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, May)----------(
/users/bdm0509/tmp/node/src)-
(09:09 $)-> Export path= $HOME/local/node/bin: $PATH
-(Bdm0509@bretts-macbook-pro Sun, May)
----------(/users/  BDM0509/TMP/NODE/SRC)-
-(09:09 $)-> CD ~/examples
--(Bdm0509@bretts-macbook-pro Sun, May)
--(/users/bdm0509/examples)-
-(09:09 $)-> Node nodefileserver.js
Server running at http://127.0. 0.1:1337/

Now you must have a rough idea of node. For this command line, there are a lot of knowledge points that need further explanation, such as what happened in Port 1337? But you just have to know that node is just a program that lets you run JavaScript. Readers don't have to dwell on how node works with JavaScript, and there's no way to introduce it, as long as you know that node can run JavaScript. And all you need to do is learn JavaScript as a programming language, without worrying that you don't understand the C language. Remember that this is the most important point, and you don't have to understand C to write the program that node can run.

interaction with the node server

We ran the nodefileserver.js on node just now. At this point you can access your local 1337 port, you can see the normal output.

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

Node can also display binary picture files. When you look back at this short program, it must feel that this is incredible. Wouldn't it be nice to use JavaScript to easily write a service program that you want? Not only that, suppose you want to write a service that can handle multiple requests (this is a hint, open four five or even 10 browser access servers), which is also easy to do. What's fascinating about node is that you can use very simple and obscure JavaScript programs to accomplish the results you want.

Quick Start Manual

The topic around node is always worth a little more time to discuss than just running on the server side of the code. Anyway, let's start with a piece of code, and look at the Nodefileserver.js file and observe the code:

var http = require ("http");
Http.createserver (function (req, res) {
    res.writehead ({"Content-type": "Text/plain"});
    Res.end ("Hello world\n");
Listen (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 of programmers. In fact, this function is also mentioned in the COMMONJS specification, as mentioned in the discussion of the JavaScript module concept , and Davd Flanagan was mentioned in a cool implementation in 2009. In other words, require () may be a novelty to you, but it is not a function that node randomly adds, and he is the core concept of modular programming using JavaScript, and node has been able to perform 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 decorate the request too much, simply outputting a string "Hello world" as a request response in Text/plain format. This logic is very simple.

In fact, this shows the standard mode of using node:

Define the type of interaction and obtain a variable to handle this interaction (via require ()).
Create a new service (via Createserver ()).
Binds a callback to the service to process the request. The function that includes processing the request should include a request ..., and a response
Notifies the server to start the service, where you need to specify the IP and port (via listen).

the confusion of the interpreter

While it's easy to use JavaScript to implement a service in this way (regardless of whether the virtual machine running the code actually runs a C program or whatever), this begs the question: Do you need to use JavaScript to write a server? To find the answer to this question, let's consider a very typical scenario.

Processing of JSON

This is a very typical Web application where the foreground uses HTML and css,javascript for data validation and data interaction with the background. Because you are at the top of the web interaction, you use AJAX to submit data to the background and get data from the background, rather than relying solely on form submission. If you do this, you will also enjoy using JSON very much. JSON is the most popular format for transmitting data today.

So this Ajax can also be likened to "sending me information about certain guitars in an online auction site." This request reaches a server running a PHP program over the network. The PHP server has to return a lot of information to JavaScript, and that information must be sent to the client in some form of data packet that can be parsed by JavaScript. So the data can be packaged in a number of groups and then converted to JSON, like this:

$itemGuitar = Array (
    "id" => "itemguitar",
    "description" => "Pete Townshend once played this guitar while Hi s own axe ".
        Is in the shop has bits of drumkit removed from it. ",
    " price "=> 5695.99,
    " URLs "=> Array (" http://www.th Ewho.com ","
        http://en.wikipedia.com/wiki/Pete_Townshend ")
);

$output = Json_encode ($itemGuitar);
Print ($output);

Back to the client, JavaScript gets this returned packet, and as a result of the conversion, the data is programmed in JSON format. Just 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 conversion is standard, and the conversion is equivalent to each other. Next, you can convert this string to a JavaScript object and call eval (), just like this:

var itemdetails = eval ("+ jsondatastring +"));

The result is an ordinary JavaScript object whose properties are consistent with the data structure of the JSON array. Of course, since jsondatastring is usually returned by the server, it is often necessary to resolve the return result:

var itemdetails = eval ("+ Request.responsetext +"));

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

subtle and destructive to entity code

This little headline is really confusing, and the author here obliquely explains the benefit of node, which is that both the front end and the backend use the same language JavaScript, which is accessible when JSON parsing is used, and the current end uses JavaScript for JSON encoding, In the background using PHP for JSON decoding, how much will be due to the various languages of the JSON parsing implementation of different and bring some compatibility problems.

First, one of the major problems with this type of code is that it relies more heavily on the interpreter. In the last example, the interpreter refers to the built-in JSON parser or to the code that parses the JSON, which actually relies on two things: the Java JSON parser, the same as the Eval () parsing the response text, and the JSON parser based on PHP. The JSON parser is already included in the PHP5.2.0, but it is given in the form of external dependencies, not inside the PHP kernel.

But this is not a lot of hype about the interpreter. After all, the interpreter itself has many problems, such as parsing "I" into "I", and the element 1 in the array is interpreted as 2. Of course, there are a lot of tests before the JSON tool is officially released to ensure that there are no errors in all the complex scenarios, including the results of the resolution on the client and the resolution on the server side. In any case, this will require a lot of testing.

In any case, JSON still has a lot of practical problems.

The choice of JSON parser based on a language (JavaScript or PHP) is a big problem. In other words, the problem is not the "translation" (translation) but the "translator" (translator), which means that the rules of the JSON itself are not problematic, but rather the quality of the JSON implementations of various languages is uneven and even many bugs. When the version of a language is more stable, the application and generalization of the JSON parser based on this language will be faster. As a result, the JSON parser becomes so powerful that it can parse arbitrary and complex data structures, even if such a complex structure is not actually used at all. Conversely, in each iteration (a combination of paths and data types for each iteration), it is also possible that the JSON interpreter cannot parse the data structure (or a deep JSON path).

The following figure is the optional JSON interpreter

This is not to say that JSON itself is bad, in fact, we think that the popularity of JSON is benefiting from its application in new areas (the implication of the author is that the initial JSON implementations in the new domain are often accompanied by many problems). For new areas, we have to ask: "Does this new stuff support JSON?" "As a result, JSON needs to evolve constantly, constantly testing, and constantly compatible with new platforms." As programmers, it may be necessary to rearrange your data structure, or wait for a new version to appear to meet your needs, or simply hack JSON directly. And these are the waste of programming resources that we are talking about.

Let's say you can implement an interpreter on your own, even if you don't get cheap by "shortcut", but use JavaScript to reinvent the wheel.

And node avoids this kind of problem, the text you just read--about the PHP5.2.0 of embedded JSON, about converting objects to arrays, about how to organize data with new structures, about the implementation of new features in JSON--all this disturbing problem will no longer exist in node, Because the front end is encoded by JavaScript as JSON, the background uses JavaScript for JSON decoding, and never goes wrong.

Potential pitfalls of Eval () in JavaScript

Just as we don't have to treat node as a new language, executing a piece of code in node with an eval () is just as much (not recommended) as the eval () in JavaScript. It is well known that eval () is very dangerous. Eval () is used to perform a text representation of the code logic that can be understood as "typing SQL code directly to execute the query" in the text box, which is not safe, which is actually a malicious SQL injection. Every time the eval () executes a string, a puppy in the Midwest is shivering, and a mother on the east coast is stabbed and cursed. Eval () is very dangerous. There are a lot of information about this on the Internet, no longer repeat here. You can use the Google query "eval javascript evil" or "eval JavaScript injection" to get more information.

Of course, if you do not have any other context constraints, you are allowed to use eval () in node, so the pitfalls of eval () remain in node. After all, node's purpose is not to completely solve the eval () problem. Node is called event-based JavaScript or event-based I/O, where "event-based" is a very important concept in node. But to fully understand what is based on events and why events allow you to avoid the risk of eval (), you need to understand how JSON works in the application, as well as the unique data structures that fit into the typical Web application architecture.

Event-based Web applications

Traditional Web Form submission is a typical event-based pattern. In other words, you enter a lot of data into a Web form (the user enters a text box, click the check box, select some items from the list, and so on), and then submit the data to the server. This scenario is actually a single program event: Use post to submit form data. This is also the working principle of AJAX based Web applications.

Send large amounts of data at once

For Ajax, it is possible to have a bit of a relationship with event-based programming. There are some interactions between the client and server side that can be considered event-based. A typical scenario is to enter a provincial code that sends a request to the server to obtain the name of the city and province. There is no need to throw a lot of data at once to the server via XMLHttpRequest Ajax. But that doesn't change the reality that most web apps are based on page refreshes. Ajax has been used more extensively for many interesting visual-related interactions, quick form validation, no refresh submission data, so you can avoid loading the page again. Therefore, although a true post request was not initiated by submitting the table forms, the Post form submission can be emulated via Ajax.

Frankly speaking, this traditional Ajax interaction also hinders the innovation of AJAX programmers. Each time a request is sent (no matter how small the requested data), it will go back and forth in the network. The server must respond to this request, usually by opening a new process. So if you really are developing in an environment of an event model, you may need to initiate 10 to 15 separate small requests to keep your page and server connected, and the server will create 10 to 15 threads (perhaps less depending on the policy assigned to the thread pool when the server processes the new request), When this number is multiplied by 1000 or 10000 or 100000 (each page requires 10 requests, the more users will be able to access the page, the number of requests would be more and more), there will be memory overflow, logical interleaving conflict, network paralysis, system crashes these problems.

As a result, in most scenarios, Web applications need to maintain a minimum dependency on events. The tradeoff is that the server-side program's response returns not a tiny piece of data, but a packet with more redundant data structures, usually JSON data, and then an eval () problem. The problem, of course, is in eval (), but it is inextricably linked to the web itself and the server-line program, which includes HTTP request and response strategies (at least in this scenario) between pages and servers.

Perhaps some people disagree with the question mentioned above, because you know there are many ways to circumvent the problem of direct eval (), and you will use such things as json.parse () instead of Eval (). There are also many compelling arguments to encourage us to use eval () carefully. These things are worthy of further discussion. But anyway, if you look at eval () with too many problems like stack overflows (stacks Overflow) , you'll find that most programmers don't use eval () correctly or securely. This is indeed a problem. Because too many rookie programmers don't seem to realize just how serious the eval () problem is.

Keep sending a small amount of data

Node brings new ideas for architectural applications, and we can use event models to architect Web applications, or "small" event models based on node. In other words, you should send a large number of requests based on a large number of events, each requesting a small packet of data, or grabbing a small amount of data from the background as needed, rather than sending very few requests, each with a large amount of data. In many scenarios, you need to wake up GUI programs in most cases (Java swing Programmer's GUI knowledge store can be useful). Therefore, when the user enters the last name and name and moves to the next input box, a request has been initiated to verify that the user name entered already exists. The same is true for the verification of provincial codes, addresses and telephone numbers. Each time that occurs on a page, a request and response are generated.

What difference does it have? Why is node able to do this and circumvent existing threading problems? In fact, node is not so mysterious, node website fully explained its philosophy:

Node's goal is to provide a solution for building scalable network applications, in the Hello World example, where servers can handle many client connections at the same time. node and the operating system have a convention that if a new link is created, the operating system notifies node and enters hibernation. If someone creates a new link, it executes a callback, and each link takes up a very small (memory) stack overhead.

Node is non-blocking and does not appear to be the case of a homologous competing thread (node is very happy with the immediate request, what happened, let it happen), and when the new request arrives at the server, there is no need to do anything alone for the request. Node simply sits there and waits (the request takes place) to process the request on request. It can be implemented with very simple code, without the valuable effort of the programmer to implement a full set of server-side logic.

Yes, the chaos is inevitable.

It is worth mentioning that the problem with non-blocking systems can also occur in this programming mode: a process (not a thread) waits for a data store operation, which produces another operation to crawl the irrelevant data. This unexpected action will have an effect on the existing wait. The author's meaning is that when multiple operations occur at the same time or do not occur in a predetermined order, confusion arises, i.e. the operation itself is not atomic. Note, however, that most event-based Web programming patterns are "read-only"! You may not have encountered a "micro-request" to modify the data, or very rare. On the contrary, it is very common to verify the legality of the data and query the data through such a request. In this case, it is best to respond directly to the request. The database itself will be locked operation, generally speaking, an excellent database can be efficient to do data operations lock unlock, without the server-side program code to do more. node, however, is more efficient than the maintenance and release of the operating system's processing threads, making it unnecessary for the server to carve out a single process for the Web response.

In addition, node also plans to implement process forking, which provides engine (spec) support for more complex process Control HTML5 the WEB workers API. Similarly, if you use an event-based model to structure Web applications, your program may have at least 100 more scenarios that require thread support. Eventually you'll find that your programming and thinking patterns have changed, and your focus will be on the logic of server-side processing of requests without caring how node works.

Where node comes in

Here we discuss another Web development model, whether it's a node or an event-based programming pattern, which is irrelevant because it's so important. In short: the right remedy! In summary, different solutions are taken for different issues, regardless of whether the solution solves other problems.

Mind-set

Not only in the field of web design, but in all programming, there is a mind-set. You can describe this mindset: the more you learn and master, the more problems you can solve, and the more you will be able to apply the skills you have mastered. This seems natural, unless you delve deeper into the technology. Yes, learning new languages and new tools and using them widely is not a bad thing. But often it goes into the wrong place, because you know it, so you use it, not because the skills and tools you have are "best suited" to your business.

Let's take a look at Ajax, there's been too much discussion about Ajax. We know that Ajax provides a reliable solution for fast query requests without refreshes. Today, because of the misuse of Ajax, the traditional form submission is too much replaced. We meet a new technology, learn it, master it, apply it, and then "abuse it." After all, many business scenarios require only traditional form submissions, not Ajax. Simple as it is, there are actually thousands of cases of abuse of Ajax, just because the developers of an application blindly respect Ajax.

In the same way, node also faces such a problem. When you first recognize the benefits of node, you want to use it. It's going to be a brain swap PHP or Perl programs for node. What's the result? It sucks. You're already suffering from obsessive-compulsive disorder, and you always want to use node for a scenario that violates its design: use JavaScript to submit a large amount of data to node, or return a large amount of JSON data to JavaScript via 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 these scenes are not what node is good at. node is better at handling small requests and event-based I/O, using node to resolve 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 the generation of Dynamic HTML pages. Use node to run on the server side to handle a small volume of requests. Whether it's rails or spring and a variety of server-side containers, just take it on demand. Be sure to understand what you need to solve, and take the best solution based on it, rather than solving the problem with the skills you currently have.

The simple purpose of node

The last thing to note is that as you get 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 bit. Understand the scenarios and problems that each tool applies to, and then find the most appropriate application scenario for the tool. If you want to become a Superman generalist (programmers tend to want to know everything), you are further away from the "expert", the so-called expert, which means to achieve a very good mastery in one or two aspects. Of course, every boss wants to find Superman-style generalists, but this kind of person often can not be asked.

Learning node may be a bit strenuous, but it's well worth it. Why? Because you're looking for a solution to Web applications based on JavaScript. This means that your existing JavaScript programming skills are not lost and you have to learn a new language when you need to use PHP or Perl, and node doesn't have to do that. Learning a new language is more of a problem than learning the benefits they bring.

The challenge of learning node is that you need to be more active in thinking, splitting the program into smaller, less-coupled pieces, and assembling them like an array. But node and event-based I/O do not solve all the problems, but it is certain that many key issues can only be resolved by node.

Reference Documents

Node:up and Running
The secrets of Node ' s success
Why a JavaScript hater thinks everyone needs to learn JavaScript in the next year
JavaScript spread to the edges and became permanent in the process
What is node.js and What does it does?



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.