Node. js Study Notes (2)-modularization, node. js Study Notes

Source: Internet
Author: User
Tags node server

Node. js Study Notes (2)-modularization, node. js Study Notes

Welcome to reprint, but please indicate the source: http://blog.csdn.net/sysuzjz/article/details/43987289

Thanks: nodebeginner.org

An application consists of different modules. Now we will introduce these modules one by one.

In the previous section of the server module, we used an example of using Node:
var http = require("http");http.createServer(function(request, response) {  response.writeHead(200, {"Content-Type": "text/plain"});  response.write("Hello World");  response.end();}).listen(8888);
This code is used to start a server. Http is a built-in module. The first line of code makes the local variable http assigned a value to the http module object. This is also the core module. JavaScript is specific, that is, everything is an object. A function can be used as a parameter of an object. We replace the anonymous callback function with the real-name function. In this way, we can reduce the Coupling Degree of the above example. 
var http = require("http");function onRequest(request, response) {    response.writeHead(200, {"Content-Type": "text/plain"});    response.write("Hello World");    response.end();}http.createServer(onRequest).listen(8080);
Put this code in server. js and run node server. js. The result is exactly the same as before. Further processing, we further encapsulate the function and encapsulate the server as a function.
var http = require("http");function start() {    function onRequest(request, response) {        console.log("Request received.");        response.writeHead(200, {"Content-Type": "text/plain"});        response.write("Hello World");        response.end();    }    http.createServer(onRequest).listen(8888);}start();

It is worth noting that most servers will access http: // localhost: 8888 By the way when accessing http: // localhost: 8888/favicon. ico. Therefore, the callback function may be executed twice.

The above-mentioned server module of the global module has limited functions, or we deliberately restrict the above modules so that they are only responsible for the HTTP server and do not involve specific business processing. To make each module independent and reduce coupling, we should set a global module for communication and collaboration between modules. We name it index. js. The content is as follows:
var server = require("./server");server.start();
The first statement contains the modules in server. js in the local directory. In this way, we only need to run index. js to achieve our previous results. However, we have to make some modifications to server. js to adapt to this change.
var http = require("http");function start() {    function onRequest(request, response) {        console.log("Request received.");        response.writeHead(200, {"Content-Type": "text/plain"});        response.write("Hello World");        response.end();    }    http.createServer(onRequest).listen(8888);}exports.start = start;
We can see that only the last sentence is actually changed. exports is the object returned by this module and the start method is added to the exports object. This is because the start function cannot be directly referenced by other modules, but the returned objects of the module can be exposed to other modules through the require method. In this way, other modules can be called in the global module.
When we run node index. js, we will find that the results are exactly the same as those above. The routing module generally has multiple business requirements for our applications. How can we identify different requests through URLs? This is the route. Unlike PHP, PHP is not responsible for the server, so PHP can take charge of a file for a business, and the request is also the PHP file name, such as action = "./index. php ". But different nodes, the server is also built by Node and concentrated in server. js. Therefore, we have introduced a routing mechanism. That is, all requests in the same domain are forwarded to different processing functions according to the path. This is similar to a router. We will introduce two new modules: url and querystring, which are responsible for url parsing. Similar to http modules, they are also built-in modules, so we do not need to install them. Let's take a url as an example to introduce the correspondence between each part and the two modules.
Next, we will compile the routing module. Compile the router. js file:
function route(pathname) {    console.log("About to route a request for " + pathname);}exports.route = route;
Route entries are inserted into the server module. This is because the url is from the request object in the createServer callback function.
var http = require("http");var url = require("url");function start() {    function onRequest(request, response) {        var pathname = url.parse(request.url).pathname;        console.log("Request for " + pathname + " received.");        response.writeHead(200, {"Content-Type": "text/plain"});        response.write("Hello World");        response.end();    }    http.createServer(onRequest).listen(8888);}exports.start = start;
How can they work together? This depends on the global module. Modify server. js first,
var http = require("http");var url = require("url");function start(route) {    function onRequest(request, response) {        var pathname = url.parse(request.url).pathname;        route(pathname);        response.writeHead(200, {"Content-Type": "text/plain"});        response.write("Hello World");        response.end();    }    http.createServer(onRequest).listen(8888);}
Note that the start function has an additional parameter, which is called in the onRequest function. This indicates that this function is used and the parameter is a path string. This function is actually the return object of the routing module. Modify index. js:
var server = require("./server");var router = require("./router");server.start(router.route);
In this way, we have added the routing module. In addition, the server is still active only on the server. Of course, if you think the url resolution should not be placed in the server module, you can also pass the request object as a parameter to the route function and then parse it in the router module. Although we have added the routing module to the business processing module, it does not actually do anything. Therefore, we also need a business processing module. The routing module determines which service processing function is used for execution based on the request url. Suppose we have two services: start and upload. Compile handler. js:
function start() {    console.log("Request handler 'start' was called.");}function upload() {    console.log("Request handler 'upload' was called.");}exports.start = start;exports.upload = upload;
Some obsessive-compulsive disorder patients may have discovered that, if there are many businesses, the following exports. xx = xx may be abnormal many times, which cannot be tolerated by an obsessive-compulsive disorder patient and brings difficulties to maintenance. Let's wrap it up:
function start() {    console.log("Request handler 'start' was called.");}function upload() {    console.log("Request handler 'upload' was called.");}var exportObj = {    start: start,    upload: upload};exports = exportObj;
It was very tall. Then the problem arises. How can we integrate the business processing module? Similarly, we still need to rely on global modules. Modify index. js
var server = require("./server");var router = require("./router");var handler = require("./handler");handlers['/'] = handlers['start'];server.start(router.route, handler);
It seems difficult to understand. The only problem is that the start function has another parameter, which is not required by the server module, but required by the routing module, the routing module is called in the server module. Therefore, we indirectly pass the business processing module to the routing module through the server module. Modify server. js:
function start(route, handle) {    function onRequest(request, response) {        var pathname = url.parse(request.url).pathname;        console.log("Request for " + pathname + " received.");        route(handle, pathname);        response.writeHead(200, {"Content-Type": "text/plain"});        response.write("Hello World");        response.end();    }    http.createServer(onRequest).listen(8888);}exports.start = start;
Then modify router. js:
function route(handle, pathname) {    console.log("About to route a request for " + pathname);    if (typeof handle[pathname] === 'function') {        handle[pathname]();    } else {        console.log("No request handler found for " + pathname);    }}exports.route = route;
The final form seems perfect. But there is still a small problem. Different service processing functions may have different outputs. We cannot always return the output items in each service processing function, and then deliver them to the server module for output? After all, the output depends on the response object of the createServer callback function. A better way is to pass the response object to the business processing module. The final form of server. js is:
var http = require("http");var url = require("url");function start(route, handler) {    function onRequest(request, response) {        var pathname = url.parse(request.url).pathname;        route(pathname, handler, response);        response.writeHead(200, {"Content-type": "text/plain"});        response.write("hello world");        response.end();    }    http.createServer(onRequest).listen(8080);}exports.start = start;
The routing module also makes some changes accordingly (in fact, passing a parameter, soy sauce once). The final form of router. js is as follows:
function route(handle, pathname, response) {    console.log("About to route a request for " + pathname);    if (typeof handle[pathname] === 'function') {        handle[pathname](response);    } else {        console.log("No request handler found for " + pathname);    }}exports.route = route;
The business processing module handler. js is ultimately as follows:
function start(response) {    response.writeHead(200, {"Content-type": "text/plain"});    response.write("Request handler 'start' was called.");    response.end();}function upload(response) {    response.writeHead(200, {"Content-type": "text/plain"});    response.write("Request handler 'upload' was called.");    response.end();}var exportObj = {    start: start,    upload: upload};exports = exportObj;
Some obsessive-compulsive patients may find that some code can be reused. We will continue to package:
function output(response, message) {    response.writeHead(200, {"Content-type": "text/plain"});    response.write(message);    response.end();}function start(response) {    output(response, "Request handler 'start' was called.");}function upload(response) {    output(response, "Request handler 'upload' was called.");}var exportObj = {    start: start,    upload: upload};exports = exportObj;
In this way, it will come to an end.
The above are just some simple modules with little actual content. The specific content must be filled as needed. Maybe this idea is not the best, but it is not worthless. At least, it reflects the idea of function separation and low coupling. If you have better suggestions, or find any deficiencies or errors, please submit them in the comments.

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.