A node. js Beginner's "Swim

Source: Internet
Author: User
Tags readfile install node

Three o'clock in the morning, when the console is activated, the hand is pressed on the keyboard. A glaring hint appeared on the black background, craving to receive commands. Want to toss the next node.js?node,js there's an exciting message: it can run anywhere. This gives the stack a variety of different ways to try it out. For any seasoned person, running with the command line is fun. My favorite is the ability to review stacks in the command line's secure network. The big thing is we're still talking about JavaScript, so most of you won't have any problems. So, why not start node in the console?

In this article, I'll introduce you to node. js. My goal is to be able to see the amazing parts in some difficult places. This article is a medium that outlines the stacks that are retained in the console. If you want to see the node. js Guide for Beginners, take a look at SitePoint's quality course Node.js:An Introduction.

Why is node. js?

Before we start, let's look at the "lace" news that makes node. js stand out:

    • Designed for non-blocking I/O
    • Designed for asynchronous operations
    • V8 JavaScript that drives Chrome

You probably already know the above points from a lot of places, but what do they mean? You can look at node. js as an engine that provides a lot of API for JavaScript. In traditional synchronous programming, when you have an I/O operation, the API waits before running the next instruction. I/O operations are, for example, reading a file or making a network request. Unlike node. JS, it was designed to operate asynchronously. This is a huge advantage in today's programming environment. Can you remember the last time you switched computers because of a faster single-core processor? The number of processors and the faster hard drives are more important.

In the next article, when you see the > This hint flag, it means you need to press ENTER and enter the next instruction. Also, when you run the code in this article, you need to turn on the CLI and execute the command node (note: You need to download and install node. js), so let's start!

Callback (callbacks)

First enter the following functions:

    1. >function add(a,b,callback) {var result = a+b ; callback(result);}

For novice web users, callback in JavaScript may be unfamiliar. This does not seem to be a typical OOP approach. In JavaScript, a function is an object that can accept other objects as arguments. JavaScript doesn't care what the object is, so one function can accept another object that is a function. Number of numeric parameters, changed from two to one by add () in the callback function. The callback system is quite powerful because it supports encapsulation and hides the real package. In node. js, you'll find that there are many APIs that use a callback as a parameter. You can think of a callback as a representation. The program is hidden inside, and this delegate is authorized to be dispatched to replace someone else. So the callback is like sending a man to finish the job. Given a list of parameters, it's like listing a shopping list, and then they're going to do the job themselves.

In order to play turn add ():

  1. > Add (2 , 3, (c{ Console. ( ' 2 + 3 = ' + C });
  2. > Add(1, 1, function (c) { console. Log(' is 1 + 1 = 3? ' + (c = = 3)); });

Try some new ways to play the callback. It is the foundation of some of the important APIs in node. js.

Asynchronous operation

With callbacks, we can start writing some asynchronous APIs, with a chestnut (in fact this season doesn't seem to have chestnuts to lift):

    1. > function dosomething (AsyncCallback) { asynccallback(); }
    2. > dosomething(function () { console. Log(' This runs synchronously. ') ); });

There is a synchronous operation in this exception, but for asynchronous operations in JavaScript, we have everything ready. AsyncCallback, can be delayed in some threads:

  1. > function dosomething (AsyncCallback) { setTimeout(AsyncCallback , Math. Random() + + ); }< /c4>
  2. > dosomething(function () { console. Log(' This runs asynchronously. ') ); }); console. Log(' test ');

I used the settimeout to delay the operation in the current thread. Timeout does not have a given time, so I use Math.random () to set a change time. Named DoSomething, then use Console.log (' Test ') to display the deferred action. After 1-2 seconds, you can read the popup message on the screen. My example of an asynchronous callback is unpredictable. node. JS puts it in the timesheet and continues the previous process. When the time is up, Node,js just runs to the time of the asynchronous operation and calls the callback. So you have to clear the various callbacks in your mind to better understand node. js.

In a word, in JavaScript, a callback is not always what it looks like.

Let's do something more interesting (forgive me for not finding anything interesting). Why not try looking up DNS in node. js?

  1. >Dns.Lookup(' Bing.com ', function (err, Address, Family) { Console. ( Address: ' + Address + +< Span class= "PLN" > family + + Err

This callback returns err,address,family three objects, with a focus on the return value being passed as a parameter to the callback. So this traditional is not quite the same as Var result= fn (' bing.com '). In node. js, a general overview must be obtained through callbacks and Asynchrony. You can check out [DNS node. js api][2] for more details. Is the look of DNS lookup in my console:

File I/O

Now continue, how do you write a file in Node,js? Imagine this scenario: you open a file, read the contents of the file, and then write the new content. In the modern process of computer i/o-bound (days, I do not know how to translate, know the private messages I, I change) operation is very slow. CPU processing is fast and RAM is fast. However, the hard disk reads or writes very slowly. As a result, the program runs slowly when the i/o-bound operation is performed synchronously. The workaround is to use async, such as:

  1. > var fs = require(' FS ');
  2. > fs. WriteFile(' message.txt ', ' Hello node. js ', function () { Console. Log(' Saved. ') ); }); console. Log(' Writing file ... ');

Because the operation is asynchronous, you will first see "Writing file ..." and see that the file is saved. The most common use of callback functions is well suited for this API. You can look at the document [File System api][6] section. How do you read a file? Can you guess through the precedent? Give you a little hint, the callback parameter is err and data. I suggest you try it.

Answer:

    1. > fs. ReadFile(' message.txt ', function(err, data) { console . Log(data); });

You can also pass in a encoding entry to read the Utf-8 content in the file:

    1. > fs. ReadFile(' message.txt ', {encoding: ' Utf-8 '}, function (err, data) { console. Log(data); });

The asynchronous I/O operation of the node. JS callback function looks perfect.

Web Server

So what happens on the Web server? Any good exposé (Multi-Window management tool on MacOS?) ) must run a Web service side. Suppose there is an API called Creatserver, and this API has a parameter that is the callback for request and response. You can look at the HTTP API in the documentation. Can you think of what it looks like? You need an HTTP module. Try it out in the console.

Answer:

  1. > var http = require(' http ');
  2. > var server = http. Createserver(function (request, response) { response. End(' Hello node. js '); });

Consider the web, which is a client-server with a request and response module. node. JS has a Request object from the client and a response object from the server. So the stack solves the Web puzzle with a simple callback principle. Do you remember that it was asynchronous? I hope you can combine the scattered memories, and if you look at the API documentation, we're doing pretty much the same thing. We load a module, tell it what to do and give it a parameter. The callback will work like a delegate: Perform a special task with a series of parameters.

Of course, if we can't see it in the browser, then everything is meaningless. In the CLI, add:

    1. Server. Listen(8080);

Then designate your favorite browser as: localhost:8080, I use edge.

Suppose the Requset object has a heap of information that can be obtained. To reconnect to the server, first turn it off (bring it down):

  1. > server. Close();
  2. > server = Http.< Span class= "PLN" >createserver (function ( request, Response) Span class= "pun" >{ Response. (request. Headers[ ' user-agent ' ); Server.8081

Specify the browser as: Localhost:8081.header provides you with user-agent information from the browser. We can traverse the header object:

  1. > server. Close();
  2. >Server=http.Createserver(function (Request,Response) { Object.Keys(Request.Headers).Foreach(function (Key) { Response. (key + ': ' + Request.[key] + " Response. Server.8082

This time the browser is designated as: localhost:8082. Once finished, remember to close. Otherwise the command line may produce strange running results.

    1. > server. Close();

You've learned to create a Web server from the command line. I hope you like this trip to node psychedelic.

Summarize

node. JS is a great fit for modern solutions because it's simple and lightweight. It leverages the advantages of modern hardware non-modular design. It contains the native Client-server module of the Web. It's best to run with our favorite JavaScript. What intrigued me was that the key part of the stack was not cutting edge. The Web page comes from a lightweight, easy-to-access module built earlier. If you have time, I suggest you look at Tim Berners-lees ' Design principles. In principle, JavaScript options are available for least power applies for node. js.

Original link: http://www.gbtags.com/gb/share/9522.htm

A node. js Beginner's "Swim

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.