Home >Web Front-end >JS Tutorial >NodeJS Study Notes Connect Middleware Module (2)_node.js

NodeJS Study Notes Connect Middleware Module (2)_node.js

WBOY
WBOYOriginal
2016-05-16 16:17:44875browse

1, opening analysis

Hello everyone, today’s article is mainly about a source code analysis series on the "Connect" middleware and related auxiliary middleware. I think you have also read the previous article,

Introduces the usage and purpose, and this article is also out of my own interest, so that readers can have a deeper understanding of it. If there is anything incorrect in the analysis stage, please give me some advice,

Okay! As usual, let’s get to the point. Let’s look at an example first, combined with introduction analysis, as follows:

Copy code 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) ;

Second, line-by-line analysis:

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

The "connect" middleware allows you to create "servers" in a variety of ways,

Copy code 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, Nobita!n") ;
}).listen(8888) ; // 2

So how is it done? See the source code:

Copy code The code is as follows:

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

Mount "createServer" to the global "exports", and then extend a "createServer" attribute and mount it again. The purpose is to be compatible with the native writing form,

Achieve the purpose of creating in different ways. This is also an idea that everyone can learn from in daily development.

(2) Let’s look at the second line "connect.createServer" and see what it does. See the following source code:

Copy code 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, except that "HTTPSServer" encapsulates the https method. When "createServer", you can also pass in a series of middleware, which has the same effect as the subsequent introduction, but it can only be bound to the root directory.

(3), continue to look at the third line "app.use()", what is done, look at the following source code:

Copy code 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 prototype inherited from "http server", it will replace the server's requestListener with the middleware used.

Use "connect.use(route, handle)" to add middleware to each route. These middleware "handles" will be bound to "route" and stored in a "stack", each time there is a "request" When requested,

Traverse this heap, find the "handle" corresponding to "route", and execute "handle". If "handle" finally calls "next()", it will continue to find and execute the next matching "handle".

By encapsulating "handle", it is easy to add more "middleware" based on "connect".

(4), finally take a look at "listen(8888)", what does it do?

It's very simple. By inheriting the underlying Server object, it is given the "listen" function to listen on a specific port.

 Server.prototype.__proto__ = http.Server.prototype

The following is the entire source code of "connect.js". In order to save space, all comments have been deleted, as shown below:

Just to add:

Copy code 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);
});
}
});

"Exports" the "middleware" object, and then looply define a method to the "middleware" object. This method is to directly load the .js file module in the "middleware" folder.

Use: "exports.utils.merge(exports, exports.middleware)" This sentence exports the methods in middleware directly.

Three, to summarize:

(1) Understanding the design intent of the source code will help maximize the gains in application.

(2) When looking at the source code, understand the process before paying attention to the grammatical details.

(3), learn from the clever implementation ideas in the source code, but do not over-design, design for the sake of design.

(4), we will continue to analyze related middleware tomorrow and will continue to update it. . . . . .

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn