node. JS Development Guide Reading notes (1)

Source: Internet
Author: User
Tags emit readfile

3.1 Start programming with node. js

3.1.1 Hello World

Save the following source code in the Helloworld.js file

Console.log (' Hello world! ' ); Console.log ('%s:%d ', ' hello ', 25);

Locate the file location and execute node helloworld.js. The results are as follows:

3.1.2 node. JS Command-line tool

Input: node--help can see detailed help information.

  

In addition to running scripts directly, the use of node--help shows another way to output Hello world.

  

Using node's REPL mode

REPL (Read-eval-print Loop), which is the input-evaluation-output loop.

  

After entering REPL mode, a ">" Prompt prompts you to enter, enter and press ENTER, and node. JS will parse and execute the command. If you execute a function, then REPL will also show the return value of the function below, undefined in the example above is the return value of Console.log, if you enter an error instruction, REPL will immediately display the error and output the call stack. You can exit node. JS repl mode by pressing CTRL + C two times in a row at any time.

Node proposes that REPL is a great convenience when it comes to application development, for example, we can test whether a package is working properly, invoke one of the application's modules separately, perform simple calculations, and so on.

3.1.3 Establishing an HTTP server

node. JS server architecture and PHP architecture

  

Create a file named App.js with the following code:

var http = require (' http '); http.createserver(function(req, res) {    Res.writehead ( {' Content-type ': ' text/html '});    Res.write (' );    Res.end (' <p>hello world</p> ');        }). Listen(console.log) (' HTTP server is listening at Port 3000 ')

Run node App.js and open the browser http://127.0.0.1:3000 to see what is shown in Figure 3-2.

  

Figure 3-2 HTTP server implemented with node. js

The simplest HTTP server implemented with node. JS was born. This program invokes the HTTP module provided by node. JS and listens on Port 3000 for all HTTP requests that reply to the same content. When we run this script in the terminal, we find that it does not exit as soon as Hello World ends, but waits until the CTRL + C end is pressed. This is because the event listener is created in the Listen function so that the node. JS process does not exit the event loop.

  Tips-Use Supervisor.

Installed: $ npm install-g Supervisor

If you are using a Linux or Mac, typing the above command directly is likely to have a permissions error. The reason is that NPM needs to install supervisor to the system directory, requires administrator privileges, and can be installed using the sudo npm install-g Supervisor command.

Next use the Supervisor command to start the App.js

  

3.2 Asynchronous I/O and event programming

  node. JS's biggest specific programming pattern is that asynchronous I/O (or non-blocking I/O) is tightly coupled with events. This mode differs greatly from the traditional synchronous I/O linear programming idea because the control flow is largely organized by events and callback functions , and a logic is split into several units.

3.2.1 Blocking and threading

what is blocking (block)? If a thread encounters disk read-write or network traffic (collectively referred to as I/O operations) in execution, it usually takes a long time for the operating system to deprive the thread of CPU control, suspend execution, and give the resource to other worker threads, which is called blocking. When the I/O operation is complete, the operating system relieves the blocking state of the thread and restores its control over the CPU to continue execution. This I/O pattern is the usual synchronous I/O (synchronous I/O) or blocking (Blocking I/O).

Accordingly, asynchronous I/O (asynchronous I/O) or non-blocking I/O (non-blocking I/O) Adopt a non-blocking strategy for all I/O operations. When a thread encounters an I/O operation, it does not wait for the completion of the I/O operation or the return of the data in a blocking manner , but simply sends the I/O request to the operating system and proceeds to the next statement. When the operating system completes an I/O operation, the thread that notifies the I/O operation as an event is handled by the thread at a particular time. In order to handle asynchronous I/O, threads must have an event loop, constantly checking for unhandled events, and processing them one at a time.

In blocking mode, a thread can only handle one task, and it must be multithreaded to improve throughput. Instead of blocking mode, a thread is always performing a compute operation, and the CPU core utilization used by this thread is always 100%,i/o as an event notification. In blocking mode, multithreading tends to improve system throughput because when one thread is blocked and other threads are working, multithreading can make the CPU resources not wasted by the threads in the blocking. In non-blocking mode, threads are not blocked by I/O and are always using the CPU. The benefit of multithreading is simply to take advantage of more cores in the case of multicore CPUs, and the single thread of node. JS can bring the same benefits. This is why node. JS uses a single-threaded, non-blocking event programming pattern.

Figure 3-3 and Figure 3-4 are examples of multi-threaded synchronous and single-threaded asynchronous I/O, respectively. Let's say we have a job that can be divided into two compute parts and an I/O section, and I/O parts take up much more time than calculations (usually this is the case). If we use blocking I/O, you must turn on multiple threads to get high concurrency. When using asynchronous I/O, a single thread is a competency.

Where is single-threaded event-driven asynchronous I/O better than traditional multi-threaded blocking I/O? In short, asynchronous I/O is less of a multithreaded overhead. For the operating system, the cost of creating a thread is very expensive, it needs to allocate memory, scheduling, while online Cheng switch, but also to perform memory paging, CPU cache is emptied, switching back, but also to re-read information from memory, destroying the data locality.

Of course, the disadvantage of asynchronous programming is that it does not conform to people's general programming thinking, it is easy to make control flow obscure and difficult to encode and debug.

  

3.2.2 Callback function

Let's look at how to read a file asynchronously in node. js, here's an example:

// Readfile.js var fs = require (' FS '); Fs.readfile (thefunction(err, data)    {if  ( Err)    {        console.error (err);     Else     {        console.log (data);    }}); Console.log (' End ')

In Create a new file file.txt, enter Hello world!

The results of the operation are as follows:

D:\001code\0011nodejs>node Readfile.js
End
Hello world!

node. JS also provides an API for synchronizing read files:

// Readfilesync.js var fs = require (' FS '); var data = Fs.readfilesync (' file.txt ', ' utf-8 '); console.log (data); Console.log (' end ');

The results of the operation are as follows:

D:\001code\0011nodejs>node Readfilesync.js
Hello world!

End

Comparison of running results: synchronous output reads the contents of the file, in the output end, and asynchronously is the first output end, and then output the contents of the file. The work done by the Fs.readfile call only sends an asynchronous I/O request to the operating system, and then immediately returns and executes the following statement, which enters the event loop listener event after execution. When FS receives an I/O request completion event, the event loop actively invokes the callback function to complete the subsequent work. So we'll see end first, and then we'll see the contents of the File.txt file.

3.2.3 Events

All asynchronous I/O operations of node. JS send an event to the event queue when it is finished. In the developer's opinion, the event is provided by the Eventemitter object. The callback functions of Fs.readfile and Http.createserver mentioned earlier are implemented by Eventemitter. Let's use a simple example to illustrate the use of Eventemitter:

// Event.js var Eventemitter = require (' Events '). Eventemitter; var New Eventemitter (); Event.on (function() {    console.log (' some_event occured. ') );        }); SetTimeout (function() {        event.emit (' some_event '1000);

Run this code, one second after the console output some_event occured. It's the idea that the event object registers a listener for the events some_event, and then we send events to the event object by settimeout after 1000 milliseconds some_ event, the Some_event listener is called.

node. JS's time loop mechanism
When does node. js get into the event loop? The answer is that the node. JS program starts with the event loop, ends with the event loop, and all the logic is the callback function of the event, so node. js is always in the event loop, and the program entry is the callback function for the first event in the event loop . The callback function of the event may issue an I/O request or a direct emission (emit) event during execution, and then the event loop, which checks for any unhandled events in the event queue, until the end of the program.

Unlike other languages, node. JS does not show an event loop, and functions like Ruby's Eventmachine::run () do not exist in node. js. node. js's event loop is not visible to developers and is implemented by Libev. Libev supports multiple types of events, such as Ev_io, Ev_timer, Ev_signal,
Ev_idle, etc., are eventemitter encapsulated in node. js. Each iteration of the Libev event loop, in node. js, is a Tick,libev constantly checking for active, ready-to-check time listeners to exit the event loop until it is detected and end. event, and then the event loop after execution, the event loop checks the event queue for any unhandled events until the end of the program.

Unlike other languages, node. JS does not show an event loop, and functions like Ruby's Eventmachine::run () do not exist in node. js. Node
The. js event loop is not visible to developers and is implemented by Libev. Libev supports multiple types of events, such as Ev_io, Ev_timer, ev_signal, Ev_idle, etc., which are eventemitter encapsulated in node. js. Each iteration of the Libev event loop, in node. js, is a Tick,libev constantly checking for active, ready-to-check time listeners to exit the event loop until it is detected and end.

3.3 Modules and Packages

3.3.1 What is a module
Modules are the basic components of the node. JS application, which correspond to the files and modules. In other words, a node. js file is a module that can be a JavaScript code, JSON, or a compiled C + + extension.
In the previous example, we used the var http = require (' http '), where HTTP is a core module of node. JS, internally implemented in C + +, and externally in JavaScript, we get this module through the Require function, You can then use the objects in them.

3.3.2 Creating and loading modules
(1) Create a module
In node. js, creating a module is very simple, because a file is a module, and the only thing we need to focus on is how to get the module in other files. node. JS provides exports and require two objects, where exports is the interface that the module exposes, and require is used to obtain an interface from the outside of a module, the exports object of the acquired module.
Let's take an example to understand the module. Create a Module.js file with the following content:

// Module.js var  function(thyname) {  =function() {  console.log (' Hello ' + name);}

Under the same directory, create the getmodule.js with the following content:

// Getmodule.js var mymodule = require ('./module '); Mymodule.setname (' byvoid '); Mymodule.sayhello ();

Running node Getmodule.js results in the following:

Hello Byvoid

(2) One-time loading

/* ===============================================# last modified:2014-08-27 13:55# filename:loadmodule.js# Description: Tanjiga Load Example =================================================*/var hello1 = require ( './module '); Hello1.setname (' BYVoid1 '); var hello2 = require ('./module '); Hello2.setname (' BYVoide2 '); Hello1.sayhello ();

The result of running node Loadmodule.js is as follows:

Hello BYVoide2

This is because the variables hello1 and Hello2 point to the same instance, so the result of Hello1.setname is hello2.setname overwritten and the final result is determined by the latter.

(3) Cover exports

A the first method is exports. Hello

Module

/*===============================================# author:rollercoaster# last modified:2014-08-27 14:02# Filename : singleobject.js# Description: Overwrite exports example 1=================================================*/functionHello () {varname;  This. SetName =function(thyname) {name=Thyname;    };  This. SayHello =function() {Console.log (' Hello ' + name + '! '); };}; exports. Hello = Hello;

Calling code:

/* ===============================================# author:rollercoaster # last modified:2014-08-27 14:05# Filename : runsingleobject.js# Description: Call singleobject module =================================================*/   var Hello = require ('./singleobject '). Hello; New Hello (); Hello.setname (' roller coaster '); Hello.sayhello () ;

Operation Result:

Hello Roller coaster!

b The second method module.exports = Hello;

Module code:

/*===============================================# author:rollercoaster# last modified:2014-08-27 14:17# Filename : hello.js# Description:hello Module =================================================*/functionHello () {varname;  This. SetName =function(thyname) {name=Thyname;        };  This. SayHello =function() {Console.log (' Hello ' + name + '! '); }}; module.exports = Hello;

Calling code

/* ===============================================# author:rollercoaster# last modified:2014-08-27 14:17# Filename : gethello.js# Description: Call Hello module =================================================*/var Hello = require ('./hello '); New Hello (); Hello.setname (' roller coaster '); Hello.sayhello () ;

Note that the only change to the module interface is to use Module.exports = Hello instead of exports. Hello = hello. When the module is called externally, its interface object is to output the Hello object itself, not the original exports.

In fact, exports itself is merely an ordinary empty object, {}, which is specifically used to declare an interface, essentially through which a limited access interface is established within the module closure. Because it doesn't have any special place. So you can use something else instead, such as the Hello object on our example above.

It is not possible to assign a value to a module.exports by exports direct copy instead. Exports is actually just a variable that points to the same object as the Module.exports, which itself is released after the module execution ends, but module does not, so you can only change the provider by specifying Module.exports.

node. JS Development Guide Reading notes (1)

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.