Nodejs Learning Notes Connect middleware Module (ii) _node.js

Source: Internet
Author: User

First, the opening analysis

Hello everybody, today this article is mainly to "Connect" middleware and related auxiliary middleware, do a source analysis series, I want to last article everyone also looked,

Introduced the use of the way and use, and this article is also out of my interest, let the reader have a more in-depth understanding of it, such as in the analysis phase of what is not correct, please give us a lot of advice,

All right! The old rules let's get to the point. Let's take a look at an example, combining it with the introduction analysis, as follows:

Copy Code code as follows:

var connect = require ("./lib/connect");
var app = Connect.createserver ();
App.use (connect.static (__dirname + "/public"), {
maxage:0
})) ;
App.use (function (req,res,next) {
Res.end ("Hello world!");
})
. Listen (8888);
 

Second, row by line analysis:

(1), the first line, the introduction of the "Connect" module, through connect to create a HTTP|HTTPS server, to provide all the features of HTTP server.

"Connect" middleware allows you to create "server" in a variety of ways,

Copy Code code as follows:

var server = Connect.createserver (
Connect.logger ()
, connect.static (__dirname + '/public ')
) ; 1
var app = connect ();
App.use (function (req,res) {
Res.end ("Hello, male June!\n");
}). Listen (8888); 2

So how does it do that, look at the source:

Copy Code code as follows:

Exports = Module.exports = Createserver;
Exports.createserver = Createserver;

Mount "Createserver" on the global "exports" and then extend a "createserver" property to mount again, in order to be compatible with native writing forms,

Achieved the purpose of different ways of creating. This is also in peacetime development can learn from the idea.

(2) To see the second line of "Connect.createserver", did what that, look at the following source:

Copy Code code as follows:

var httpserver = require ('./http '). Server,
Httpsserver = require ('./https '). Server;
function Createserver () {
if (' object ' = = typeof arguments[0]) {
return new Httpsserver (Arguments[0], Array.prototype.slice.call (arguments, 1));
} else {
return new Httpserver (Array.prototype.slice.call (arguments));
}
};

"Httpsserver" and "httpserver" are basically consistent, just "httpsserver" encapsulation of the method of HTTPS. In the "Createserver", the same can be passed in a series of middleware, and then introduced the effect is the same, but can only be bound to the root directory.

(3), continue to see the third line "App.use ()", did what that, look at the following source:

Copy Code code as follows:

var Server = exports. Server = function Httpserver (middleware) {
This.stack = [];
Middleware.foreach (function (FN) {
This.use (FN);
}, this);
http. Server.call (this, this.handle);
};
/**
* Inherit from ' http. Server.prototype '.
*/
server.prototype.__proto__ = http. Server.prototype;

Connect is a prototype that inherits from the HTTP server, and replaces the server's Requestlistener with the middleware used to use it.

By adding middleware to each route via "Connect.use (route, handle)", these middleware "handle" are stored in a "stack" with the "route" binding, and each time a "request" is requested,

Iterate over the heap, find the "handle" of the corresponding "route", execute "handle", and if "handle" finally calls "next", it will continue to look for and execute the next matching "handle".

by encapsulating "Handle", it is easy to add more "middleware" on the "connect" basis.

(4) and finally look at "Listen (8888)", what does it do to work that?

Quite simply, by inheriting the underlying server object, the "Listen" function is given to listen for specific ports.

server.prototype.__proto__ = http. Server.prototype

The following is the "Connect.js" of all the source code, in order to save space, the comments have been deleted, the following figure:

Add:

Copy Code code as follows:

Fs.readdirsync (__dirname + '/middleware '). ForEach (function (filename) {
if (/\.js$/.test (filename)) {
var name = filename.substr (0, Filename.lastindexof ('. '));
EXPORTS.MIDDLEWARE.__DEFINEGETTER__ (name, function () {
return require ('./middleware/' + name);
});
}
});

The "Middleware" object is "exports", and then the loop defines a method for the "middleware" object, which loads the. js file module directly in the "middleware" folder.

Use: "Exports.utils.merge (exports, exports.middleware)" This sentence will be middleware directly exports the method.

Third, summarize:

(1), understand the design intent of the source code, help to maximize the harvest in the application.

(2), look at the source code, understand the process and then buckle the grammatical details.

(3), draw on the ingenious realization idea in the source code, but do not transition design, design for design.

(4), tomorrow continue to analyze the relevant middleware, constantly updated ...

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.