Reading notes: The Lucid node. js

Source: Internet
Author: User
Tags emit


>> in layman node

node. JS is a JS run environment written by C + +

Browser: Rendering engine + JS engine

JS running environment at the back end

node. JS uses the Google V8 engine, while providing many system-level APIs (file manipulation network programming ... )

node. JS uses event-driven asynchronous programming to design for network services

Browser-side JS has a variety of security restrictions

Most of the APIs that node. JS provides are event-based, asynchronous styles.

The advantage of node. JS: Make full use of system resources, execution code will not be blocked to wait for the completion of an operation, this design is very suitable for back-end network service programming. Through event registration, callbacks can improve the utilization of resources and improve performance.

To facilitate server development, node. JS has a number of network modules:
HTTP, HTTPS, DNS, NET, UDP, TLS, etc., Help to build a Web server quickly.

Node. JS Features: Event-driven, asynchronous programming, single process, single thread.
node. JS internally efficiently maintains the event loop queue with a single thread, without too much resource usage and context switching.

How does node. js, with its single-core performance, take advantage of multicore CPUs? It is recommended that you run multiple node. JS processes to coordinate tasks with some kind of communication protocol.

The anonymous and closure features of JavaScript are ideal for event-driven, asynchronous programming.

The thing that node. JS is best at is communicating with other services. Because node. JS is event-based, non-blocking, it is ideal for handling concurrent requests; The disadvantage is that node. JS is a relatively new open source project, so it's not stable, has changed, and lacks enough third-party library support.

The well-known project hosting site GitHub also tried the Node app (nodeload). Projects using node. JS also have MyFox

Node Library Socket.io

>> installation and configuration of node. js
Windows version has compiled the node. JS installation package Nodejs.msi, after installation in the node command line environment input NODE-V, there is a version number output, then the installation is OK.

NPM (Node Package Manager) Nodejs packages Manager. With NPM We can install Nodejs third-party libraries.

Unix/linux Installing NPM:
Curl Http://npmjs.org/install.sh | sudo sh
Get the shell script and give the SH command execute with sudo permission.
After installation, enter NPM carriage return, such as the output help to indicate that the installation was successful.

Installing third-party libraries with NPM: underscore
NPM Install underscore
Because some special network environment with NPM to install third-party library, easy to die; You can install it through a mirrored NPM repository, such as:
NPM--registry "http://npm.hacknodejs.com/" Install underscore

Set as default NPM resource library:
NPM Config Set registry "http://npm.hacknodejs.com" and can be set directly after NPM install underscore

Install NPM under window:
Download the newer Nodejs.msi (v0.10 ...) When the package is installed and installed, NPM is also installed by default.

You can view NPM help information by entering NPM enter at the command line.


--------------------------------------------------------
The difference between the JS module file in node. js and the JS file loaded by the script tag is that the variables declared in node. JS's module file are within the closure, do not pollute the global environment, and need to be externally called interfaces to hang on the exports.

>> event mechanism for node. js
Node. JS Features: evented I/O for V8 JavaScript (event-driven I/O based on V8 engine)

Event Module (events. Eventemitter) is a simple implementation of the event listener pattern. Has a method:
Addlistener/on, once, RemoveListener, removealllisteners, emit ...

node. JS events are different than events on the front-end DOM tree, there are no bubbling and layer-by-level captures, and naturally no preventdefault (), Stoppropagation (), Stopimmediatepropagation () Methods for handling event delivery

Event Listener mode is also an event hook mechanism that uses event hooks to export internal data and state to external callers.


var options = {
Host: ' Www.google.com ',
PORT:80,
Path: '/upload ',
Method: ' POST '
};

var req = http.request (options, function (res) {
Console.log (' STATUS: ' + res.statuscode);
Console.log (' HEADERS: ' + json.stringfy (res.headers));

Res.setencoding (' UTF8 ');
Res.on (' Data ', function (chunk) {
Console.log (' BODY: ' + chunk);
});

});

Req.on (' Error ', function (e) {
Console.log (' Problem with request: ' + e.message);
});

Write data to request body
Req.write (' data\n ');
Req.write (' data2\n ');
Req.end ();

Note: If you add more than 10 listeners to an event, you get a warning because the designer thinks that too many listeners can cause a memory leak. Call this statement to cancel the limit of 10 listeners: Emitter.setmaxlistener (0);

If the error event is triggered by runtime errors, it is passed to the error listener, and if no error listener is set, an exception is thrown, and if the exception is not caught, it will cause an exit.

> How to inherit the event. The Eventemitter class, such as the node. JS Stream object inherits the Eventemitter class:
Class-Type Inheritance
function Stream () {
Event. Eventemitter.call (this);
}
Util.inherits (Stream, event. Eventemitter);

Util.inherits should be the following to implement the prototype chain
Util.inherits = function (subclass, superclass) {
function F () {}
F.prototype = Superclass.prototype;
Subclass.prototype = new F;
SubClass.prototype.constructor = subclass;
}

> Collaboration between multiple events
In large applications, the separation of data sources and Web servers is inevitable. The benefits are: the same data source developed a variety of rich client programs, pull data from multiple data sources, rendering to the client.
node. JS is adept at simultaneously initiating requests to multiple data sources concurrently.
Parallel requests:
Api.getuser (' username ', function (profile) {
Got the profile
});

Api.gettimeline (' username ', function (timeline) {
Got the timeline
});

Api.getskin (' username ', function (skin) {
Got the Skin
});

There is a problem here: Requests can be emitted in parallel, but how do you control the order in which the callback functions are executed?

If you change this:
Api.getuser (' username ', function (profile) {
Api.gettimeline (' username ', function (timeline) {
Api.getskin (' username ', function (skin) {
Todo
});
});
});

This causes the request not to be emitted in parallel.

node. JS does not natively support a coordinated approach to multiple events, and requires a third-party library. Such as:

var proxy = new Eventproxy ();
The all method acts: After the event is listened to, the callback is executed and the received parameter is listened to the incoming callback
Proxy.all (' profile ', ' timeline ', ' Skins ', function (profile, timeline, skin) {
Todo
});

Api.getuser (' username ', function (profile) {
Proxy.emit ("Profile", profile); Trigger the event profile and pass in the actual parameter profile
});

Api.gettimeline (' username ', function (timeline) {
Proxy.emit (' Timeline ', timeline);
});

Api.getskin (' username ', function (skin) {
Proxy.emit (' skin ', skin);
});

Another solution to multi-event collaboration: Jscex (code can be written in a synchronous way, executed asynchronously)
Such as:
var data = $await (Task.whenall ({
Profile:api.getUser (' username '),
Timeline:api.getTimeline (' username '),
Skin:api.getSkin (' username ')
}));

Use: Data.profile, Data.timeline, Data.skin
Todo

> Solving avalanche problems with event queues
Avalanche problem: In the context of cache failure, a large number of concurrent access to the database query at the same time, the database can not withstand, resulting in the overall site is slow.

See the solution for adding a status lock:
var status = ' Ready ';
var select = function (callback) {
if (status = = = ' ready ') {
Status = ' pending '; Locked
Db.select (' SQL ', function (results) {
Callback (result);
Status = ' ready '; Unlock
});
}
}

When you call the Select method multiple times, a select is not processed during the lock, so the event queue should be used to resolve it.

var proxy = new Eventproxy ();
var status = ' Ready ';
var select = function (callback) {
Proxy.once (' selected ', callback);//Press All the requested callbacks into the event queue
if (status = = = ' ready ') {
Status = ' pending ';
Db.select (' SQL ', function (result) {
Proxy.emit (' selected ', result);
Status = ' ready ';
});
}
}

>> asynchronous I/O implementation of node. js
Synchronization: Subsequent tasks in the program need to wait for I/O to complete and the CPU is not fully utilized during the wait.
There are 2 ways to make the most of CPU by implementing I/O parallelism: multithreaded but process, single-threaded multi-process

GetFile (' File_path '); Time Consuming M
Getfilefromnet (' url '); Time Consuming N
Synchronous I/O, requires m+n, asynchronous I/O, max (m,n)
asynchronous I/O is important in a distributed environment and can significantly improve performance.

> Asynchronous I/O and polling technology
For non-blocking I/O operations, to read the full data, the application has to poll multiple times to ensure that the data reads are complete and then proceed to the next step. The disadvantage of polling technology is that the application actively calls multiple times, consuming more CPU time slices.

>> asynchronous I/O model for node. js
Fs.open = function (path, flags, mode, callback) {
callback = Arguments[arguments.length-1];
if ((typeof callback)!== ' function ') {
callback = NoOp;
}

mode = Modenum (mode, 438); /* 438 = 0666 */
Binding.open (Pathmodule._makelong (path), stringtoflags (Flags), mode, callback);
}

>> String Buffer

var fs = require (' FS ');
var rs = fs.createreadstream (' testdata.md ');
var data = ';
Rs.on (' Data ', function (trunk) {
Data + = trunk; Trunk is a buffer object
});

Rs.on (' End ', function () {
Console.log (data);
});

NPM install bufferhelper;
Bufferconcate.js:
var http = require (' http ');
var bufferhelper = require (' Bufferhelper ');
Http.createserver (function (req, res) {
var bufferhelper = new Bufferhelper ();
Req.on (' Data ', function (chunk) {
Bufferhelper.concat (chunk);
});

Req.on (' End ', function () {
var html = Bufferhelper.tobuffer (). toString ();
Res.writehead (200);
Res.end (HTML);
});
});

>> Connect module (node. JS Web Framework)
The streaming process of middleware

var app = connect ();

Middleware
App.use (Connect.staticcache ());
App.use (connect.static (__diranme + '/public '));
App.use (Connect.cookieparser ());
App.use (Connect.session ());
...
App.use (function (req, res, next) {
Middleware
});

App.listen (3001);

Connect uses the use method to register the middleware into the middleware queue.

Related Article

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.