Nodejs Study notes (ii)

Source: Internet
Author: User
Tags emit readfile

node. JS callback function

The immediate manifestation of node. JS asynchronous programming is callbacks.

Asynchronous programming relies on callbacks to implement, but it cannot be said that the program is asynchronous after using the callback.

The callback function is called after the task is completed, and node uses a large number of callback functions, and all node APIs support the callback function.

For example, we can read the file while executing other commands, and after the file is read, we return the contents of the file as parameters to the callback function. This will not block or wait for file I/O operations when executing code. This greatly improves the performance of node. JS and can handle a large number of concurrent requests.

Blocking Code Instances

Create a file input.txt with the following content:

  Blog Address: http://www.cnblogs.com/gorgeous/

Create the Main.js file with the following code:

var fs = require ("FS"); var data = Fs.readfilesync (' input.txt '); Console.log (data.tostring ()); Console.log ("program execution ends!");

The result of the above code execution is as follows:

$ node Main.js
Blog Address: http://www.cnblogs.com/gorgeous/
Program execution ends!
Non-blocking Code instances

Create a file input.txt with the following content:

Blog Address: http://www.cnblogs.com/gorgeous/

Create the Main.js file with the following code:

var fs = require ("FS"); Fs.readfile (' Input.txt ', function (err, data) {    if (err) return Console.error (err);    Console.log (Data.tostring ());}); Console.log ("program execution ends!");

The result of the above code execution is as follows:

$ node Main.js program execution ends!
Blog Address: http://www.cnblogs.com/gorgeous/

Above two examples we understand the difference between blocking and non-blocking calls. The first instance finishes executing the program after the file has been read. In the second instance, we don't have to wait for the file to be read, so we can execute the next code while reading the file, which greatly improves the performance of the program.

As a result, blocking is performed sequentially, not blocking is not required in order, so if you need to handle the parameters of the callback function, we need to write it inside the callback function.

What if there are several layers of callbacks? There are several solutions, often see the above express reference, and later I writenode. js Event Loop

node. JS is a single-process single-threaded application, but it supports concurrency through events and callbacks, so performance is very high.

Each of the APIs for node. JS is asynchronous and runs as a standalone thread, using an asynchronous function call, and handling concurrency.

node. js basically all of the event mechanisms are implemented using the Observer pattern in design mode.

The node. JS single thread resembles an event loop that enters a while (true) until no event observer exits, and each asynchronous event generates an event watcher that invokes the callback function if an event occurs.

Event Driver

node. JS uses the event-driven model, when the Web server receives the request, shuts it down and processes it, and then goes to service the next Web request.

When this request is completed, it is put back into the processing queue, and when it arrives at the beginning of the queue, the result is returned to the user.

This model is very efficient and extensible because webserver always accepts requests without waiting for any read and write operations. (This is also known as non-blocking IO or event-driven IO)

In the event-driven model, a main loop is generated to listen for events and trigger a callback function when an event is detected.

The entire event-driven process is so simple. Somewhat like the Observer pattern, the event is equivalent to a subject (Subject), and all the processing functions registered to the event are equivalent to the Observer (Observer).

node. JS has multiple built-in events, and we can bind and listen to events by introducing the events module and instantiating the Eventemitter class, as in the following example:

Introduce the events module var events = require (' events ');//Create Eventemitter object var eventemitter = new events. Eventemitter ();

The following program binds event handlers:

handler for binding events and Events Eventemitter.on (' EventName ', eventHandler);

We can trigger events through the program:

Trigger Event Eventemitter.emit (' EventName ');
Instance

Create the Main.js file, as shown in the following code:

Introduce the events module var events = require (' events ');//Create Eventemitter object var eventemitter = new events. Eventemitter ();//Create event handler var Connecthandler = function connected () {   console.log (' connection succeeded. ');     Trigger Data_received Event    eventemitter.emit (' data_received ');} Bind Connection Event handler Eventemitter.on (' Connection ', Connecthandler); Use the anonymous function to bind data_received event Eventemitter.on (' data_received ', function () {   console.log (' Data received successfully. ‘);});/ /Trigger Connection Event Eventemitter.emit (' Connection '); Console.log ("program execution is complete. ");

Next let's execute the above code:

$ node Main.js connection succeeded. Data received successfully. Execution of the program is complete.
How does the Node application work?

In the Node application, the function that performs the asynchronous operation takes the callback function as the last parameter, and the callback function receives the error object as the first argument.

Let's take a look at the previous example and create a input.txt with the following file contents:

Blog Address: http://www.cnblogs.com/gorgeous/

Create the Main.js file with the following code:

var fs = require ("FS"); Fs.readfile (' Input.txt ', function (err, data) {   if (err) {      console.log (err.stack);      return;   }   Console.log (Data.tostring ());}); Console.log ("program execution Complete");

The above program Fs.readfile () is an asynchronous function used to read the file. If an error occurs during the reading of the file, the error Err object will output an error message.

If no error occurs, ReadFile skips the output of the Err object, and the contents of the file are output through the callback function.

Execute the above code and execute the result as follows:

Program execution Complete
Blog Address: http://www.cnblogs.com/gorgeous/

Next we delete the Input.txt file, and the execution results are as follows:

Program execution complete error:enoent, open ' input.txt '

The error message is output because the file input.txt does not exist.

node. JS REPL (Interactive interpreter)----------> has nothing to do with callbacks, it's a terminal

    • Read -read user input, parse input JavaScript data structure and store in memory.

    • execution -execution of input data structures

    • Print -Output results

    • Loop -loop operation the above steps until the user two times press the ctrl-c button to exit.

Node's interactive interpreter can debug Javascript code very well.

Start learning REPL

We can start Node's terminal by entering the following command:

In this case, we can enter a simple expression after > and press ENTER to calculate the result.

Simple expression arithmetic

Next, let's perform a simple math operation in the command-line window of node. js REPL:

$ node> 1 +45> 5/22.5> 3 * 618> 4-13> 1 + (2 * 3)-43>
Using variables

You can store the data in a variable and use it when you need it.

Variable declarations require the use of the var keyword, which is printed directly if the var keyword variable is not used.

Variables that use the var keyword can use Console.log () to output variables.

$ node> x = 1010> var y = 10undefined> x + y20> console.log ("Hello World") Hello worldundefined> Console.log ("www.runoob.com") www.runoob.comundefined
Multi-line expression

Node REPL supports the input of multi-line expressions, which is a bit like JavaScript. Next, let's perform a do-while loop:

$ node> var x = 0undefined> do {.... console.log ("x:" + x); ...} while (x < 5);x:1x:2x:3x:4x:5undefined>

... The symbol of the three points is automatically generated by the system, you can enter the line after the return. Node automatically detects whether it is a continuous expression.

Underscore (_) variable

You can use an underscore (_) to get the result of an expression:

$ node> var x = 10undefined> var y = 20undefined> x + y30> var sum = _undefined> console.log (sum) 30undefine D>
REPL command
    • Ctrl + C -exits the current terminal.

    • Ctrl + C Press two times -Exit Node REPL.

    • Ctrl + D -exits Node REPL.

    • up/down arrow -View input history commands

    • tab -Lists the current command

    • . Help-List use commands

    • . Break-Exit multi-line expression

    • . Clear -Exit multi-line expression

    • . Save filename -Saves the current Node REPL session to the specified file

    • . Load filename -Loads the contents of the file in the current Node REPL session.

Stop REPL

We have already mentioned that pressing two times CTRL + C key will exit REPL:

$ node> (^c again to quit) >

Nodejs Study notes (ii)

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.