node. JS Learning Note (4)--except for the HTTP (Server and Client) section

Source: Internet
Author: User
Tags emit readfile

Many of the portal's books will introduce the node feature: single-threaded, asynchronous I/O, event-driven.

node is not a language, it is a development platform running on the server side, the official language is JavaScript.

Blocking and threading:

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 take the CPU control of the thread, suspend execution, perform this I/O operation, and give the resource to other worker threads, which is called blocking. When the other finishes, the system resumes its control of the CPU and continues to execute, which is synchronous I/O or blocking I/O.

So, under this pattern, a thread can handle only one task, either a compute operation, an I/O operation, and so on. Each time a number of requests are sent, you must add more threads to respond.

Similarly, in an asynchronous or non-blocking manner, the system blocks all I/O operations, and instead reports this time-consuming and resource-intensive operation to the OS, it continues with the next statement. When the OS finishes this I/O operation, the thread notifies the original request to mount I/O operations as an event, and the thread processes the thing at a specific time. Therefore, the required thread must have an event loop and constantly check for unhandled events.

So in this mode, the CPU's core utilization is always 100%,i/o in the form of an event notification.

Summary: Multi-threaded synchronous I/O blocking mode responds to more requests through the threading process, with the benefit of using more cores in the case of multicore CPUs.

Single-threaded mode asynchronous I/O non-blocking a thread is always performing a compute operation, which makes the CPU's core utilization at 100%. Utilize multi-core CPUs through functional partitioning.

Isn't that the same as the same? What is the reason node uses the latter?

The trick of a single thread is that you don't have to create more threads, which can save resources wasted by creating threads. The theory is that it is very resource-intensive to add a new thread.

About asynchronous I/O (disk read-write or network communication) and event-driven:

Node maintains an event queue.

Normal way to query database operations:

Res=db.query (' SELECT * from * ');

Res.output ();

Node Solution:

Db.query (' SELECT * from * ', function (res) {

Res.output ();

});

The callback function is used above. Implements a non-blocking way of requesting.

Disadvantages: A complete logic split into events, to increase the difficulty of debugging the development, the solution is mentioned later.

Two examples of reading files via node Fs.readfile API (asynchronous (callback function implementation) and synchronous):

var fs = require (' FS ');

Fs.readfile (' file.txt ', ' utf-8 ', function(err, data) {

if (ERR) {

Console.error (ERR);

} Else {

Console.log (data);

}

});

Console.log (' end. ');

var fs = require (' FS ');

var data = Fs.readfilesync (' file.txt ', ' utf-8 ');

Console.log (data);

Console.log (' end. ');

The output data is in a different order. But there's no difference in functionality.

About Modules:

Node provides a exports and require two objects. Exports is the interface that the module exposes, and require is the interface used to get the module.

Instance:

Create two files, one as the outside module to load Module.js, and the other is the program's entry file getmodule.js.

Module.js:

var name;

Exports.setname=function (name) {

Name=name;

};

Exports.sayhello () {

Console.log (' hello ' +name);

};

Getmodule.js:

var test=require ('./module.js ');

Test.setname (' Zhou ');

Test.sayhello ();

Node Getmodule.js

Hellozhou

This enables the encapsulation of the interface. Module.js through the Exports object bar two functions as the indirect interface, in the getmodule.js through the Require load a module, then you can directly access the module of the exports object member functions.

To Create a package :

A package is a deeper abstraction on a module basis.

Below, you can encapsulate a folder Somepckage as a module. In this file there should be a index.js file, like Module.js. Then in the Getmodule.js file, you can use the Var a=require (./package) directly;

You can then access the functions inside the index.js via a.xxxx. The pro-test is feasible.

Off topic: About the pros and cons of global installation dependency packages and the selection of directory installation dependencies.

The overall benefit is the degree to which program reuse can be increased. Avoid the same content that exists in multiple replicas. The disadvantage is that it is difficult to handle different version dependencies.

The local benefit is that there is no problem that different programs rely on different versions of packages. At the same time reduce the package author's API compatibility pressure, but the flaw is to install each one, very cumbersome.

Node has both global and local options.

The reason we chose to install globally is that the local installation does not register the PATH environment variable. For example, a supervisor installed under one project will not work in another project.

However, it is a sad thing to use a package under the global installation that cannot be accessed through require. Locally installed can be accessed through require, but the PATH environment variable is not registered, the global installation cannot be accessed through require, but the PATH environment variable is registered.

In summary, when we want to take a package as part of the project runtime, we get it through local mode, if we want to

Used at the command line, the global mode installation is used.

There is also how to publish your NPM package for use by people all over the world.

The following describes node the core module. (Global variables, common tools, event mechanisms, file systems, HTTP servers and clients)

Global variables

Global objects: Objects that can be accessed in any part of a program are global variables, similar to the global installation described above. The PATH environment variable is added.

Global objects and all of their properties are global variables and can be accessed arbitrarily.

In browser JavaScript, window is a global variable, and we can use window.open anywhere ...

node, the global object is globals. All global variables are properties of global. including console,process and so on.

Process : (global variable, globals one of the properties)

Function: An object that describes the current node process and provides a simple interface to the operating system.

PROCESS.ARGV: Command line parameter array, you can return the command line parameter is an array, the first element of the array is node, the second is the file directory, and later for the running parameters;

Process.stdout: Standard output stream, Process.stdout.write () than Console.log (), closer to the bottom;

Process.stdin: standard input stream;

Process.nexttick (callback): Sets a task for the event loop, and node calls callback when the next event loop is appropriate. More efficient than settimeout (fn,0).

Console : Used to provide console standard output

Console.log ():

Console.log (' Hello world ');

Console.log (' Byvoid%diovyb ');

Console.log (' Byvoid%diovyb ', 1991);

Output:

Hello World

Byvoid%diovyb

Byvoid1991iovyb

Console.error (): Output to standard error stream

Console.trace (): Outputs the current call stack to the standard error stream.

Common tools

var util = require (' util ');

Util.inherits

Util.inherits (constructor, Superconstructor) is a function that implements prototype inheritance between objects.

Util.inherits (Sub, Base);

Sub inherits from base;

Util.inspect

Util.inspect (Object,[showhidden],[depth],[colors]) is a method that converts any object to a string, typically for debugging and error output. It accepts at least one parameter, object, which is to be converted.

Depth: Maximum number of recursive layers, default two tiers, NULL unlimited times until traversal is complete.

Event-driven modules Events

Events is the most important module of node. are dependent on almost all modules.

Event emitter

The events module provides only one object: events. Eventemitter. The core is the encapsulation of event launches and event listeners.

var events = require (' events ');

var emitter = new events. Eventemitter ();

Related APIs:

Emitter.on (Event,listener): registers a listener for the Enent event, accepts string event and a callback function listener;

Emitter.emit (Event,[arg1],[arg2],[arg3],[arg4]) : launch event, pass a number of optional parameters to the event listener's parameter table; Emitter.emit (' error '); When error is fired, eventemitter rules if the listener is unresponsive, node. js will take it as an exception, exit the program and print the call stack.

eventemitter.once (event, listener) registers a single listener for the specified event, that is, the listener is fired at most once, and the listener is released immediately after the trigger.

Eventemitter.removelistener (event, listener) removes a listener for the specified event, listener must be a listener that the event has already registered.

eventemitter.removealllisteners ([Event]) removes all listeners for all events and, if specified, removes all listeners for the specified event.

Quite abstract, let's take a good example:

var events = require (' events ');

var emitter = new events. Eventemitter ();

Emitter.on (' someevent ', function(arg1, arg2) {//register a listener for the Someevent event-an anonymous callback function.

Console.log (' Listener1 ', arg1, arg2);

});

Emitter.on (' someevent ', function(arg1, arg2) {/For the Someevent event also registers a listener-an anonymous callback function.

Console.log (' Listener2 ', arg1, arg2);

});

Emitter.emit (' someevent ', ' Byvoid ', 1991);//Launch enent event, pass two parameters to the event listener parameter table

Results:

Listener1 Byvoid 1991

Listener2 Byvoid 1991

Summary: Emitter uses. On to register two event listeners for the Someevent event, and then uses the. Enit to emit an event someevent and pass two parameters to the event listener. The two event listener callback functions are then called.

file Manipulation module ( FS ):

Node provides both asynchronous and synchronous methods for file operations.

Async mode:

Fs.readfile (Filename,[encoding],[callback (Err,data))

File name, encoding (default is binary), callback function. Data is the file content.

var fs = require (' FS ');

Fs.readfile (' content.txt ', function(err, data) {

if (ERR) {

Console.error (ERR);

} Else {

Console.log (data);

}

});

Output (assuming the source file is Utf-8 encoded):

<buffer, E6, E6 9c ac e6, E4, bb b6 e7 A4 ba e4 be 8b>

Specify the encoding method:

var fs = require (' FS ');

Fs.readfile (' Content.txt ', ' utf-8 ', function (err, data) {

if (err) {

Console.error (err);//If you run an error, err will be the object of error.

} else {

Console.log (data);

}

});

Output:
Example text text file

To complement the callback function:

node. js Asynchronous programming Interface habit is to use the last parameter of a function as a callback function, usually a function has only one callback function. The callback function is the first of the actual arguments is err, and the rest of the arguments are the other returned content. If no error occurs, The value of err will be null or undefined. If an error occurs,err is usually an instance of the Error object.

Synchronization mode:

Fs.readfilesync (Filename,[encoding]).

Fs.open

Fs.open (Path,flags, [mode], [Callback (Err, FD)])

Path, flag is the way to confirm the opening of the file (read-write, read-only, create or not), mode default 0666, callback function returns a file descriptor FD.

Fs.read

Fs.read (Fd,buffer, offset, length, position, [Callback (Err, Bytesread,buffer)])

Provides a lower-level interface than Fs.readfile.

(File descriptor, write buffer point, buffer write offset, read byte count, read start position, callback function pass two parameters--bytes and buffer object)

Reference: "node. JS Development Guide"

(To be continued, please indicate the error)

Node. JS Learning Note (4)--except for the HTTP (Server and client) Section

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.