NodeJS Study Notes: Connect middleware module (ii) _ node. js-js tutorial

Source: Internet
Author: User
In this article, we will continue to introduce how to use and use the connect middleware in nodejs. I. Opening Analysis

Hello everyone, this article is mainly about the source code analysis series for the "Connect" middleware and related auxiliary middleware,

I introduced the usage and usage, and this article also gave readers a deeper understanding of it out of their interest. For example, what is wrong during the analysis stage, please kindly advise,

Okay! Old rules let us go into the question. Let's take a look at an example and use the introduction analysis as follows:

The Code is 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 );

 

2. Row-by-row analysis:

(1) The first line introduces the "connect" module and creates an http | https server through connect to provide all functions of the http server.

"Connect" middleware allows you to create "server" in multiple ways ",

The Code is as follows:


Var server = connect. createServer (
Connect. logger ()
, Connect. static (_ dirname + '/public ')
); // 1
Var app = connect ();
App. use (function (req, res ){
Res. end ("Hello, Grand Lord! \ N ");
}). Listen (8888); // 2

Then, let's look at the source code:

The Code is as follows:


Exports = module. exports = createServer;
Exports. createServer = createServer;

Mount "createServer" to the global "exports", and then extend the "createServer" attribute to be mounted again to ensure compatibility with native writing forms,

Different methods are created. This is also an idea that everyone can learn from during normal development.

(2) Let's take a look at the second line "connect. createServer". Let's look at the source code below:

The Code is 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 the same, but only the https method encapsulated by "HTTPSServer. When "createServer" is used, it can also be passed into a series of middleware. The effect is the same as that introduced later, but it can only be bound to the root directory.

(3) continue to check the third line of "app. use ()". See the source code below for what you have done:

The Code is 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 inherited from "http server". It replaces the requestListener of the server with the middleware used.

Connect. use (route, handle) "to add middleware to each route. These middleware" handle "will be bound to" route "and saved in a" stack, when a "request" request is sent,

Traverse the heap and find "handle" corresponding to "route" and execute "handle". If "handle" finally calls "next ()", the next matched "handle" will be searched and executed ".

By encapsulating "handle", you can easily add more "middleware" based on "connect ".

(4) Finally, let's look at "listen (8888)". What does it do?

It is easy to listen to a specific port by inheriting the underlying Server Object and granting the "listen" function.

Server. prototype. _ proto _ = http. Server. prototype

Below are all the source code of "connect. js". To save space, all comments have been deleted, for example:

Add:

The Code is 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 );
});
}
});

Call the "middleware" object "exports" and define it cyclically to the "middleware" object. This method is to directly load the. js file module in the "middleware" folder.

Use the "exports. utils. merge (exports, exports. middleware)" statement to export the methods in middleware.

Iii. Summary:

(1) Understanding the design intent of the source code helps to maximize the benefits of the application.

(2) when reading the source code, understand the process and deduct the syntax details.

(3) draw on the clever Implementation ideas in the source code, but do not design the transition.

(4) continue to analyze and update the middleware tomorrow... ...

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.