Lesson six self-routing improvements, responding to the paths of different requests

Source: Internet
Author: User

1 server.js

var http = require (' http ');
var url = require (' URL ');
function Start (Route,handler)
{
function ONrequest (req,res)
{
var pathName = Url.parse (req.url). PathName;
The route function that the client page passes over
Route (Pathname,handler,res);
}
Http.createserver (ONrequest). Listen (5000);
Console.log (' Server Started ');
}

Exports.start = start;

2 Route.js

Function route (pathname,handler,res)
{
Console.log (' Router user request URL: ' +pathname+ ' \ n ');
if (typeof handler[pathname]=== ' function ')
{
Handler[pathname] (res);
}else{
Console.log (' No request handler found for ' +pathname);
}
}
Exports.route = route;

3 Requesthandlers.js

var exec = require (' child_process '). exec;
Using response direct output will not block other requests
function Start (res) {
EXEC ("Ls-lah", function (Error, stdout, stderr) {
Res.writehead (200,{"Content-type": "Text/plain"});
Res.write (' Start ... ');
Res.write (stdout);
Res.write (' End ... ');
Res.end ();
});
}

function upload (res) {
Res.writehead (200,{"Content-type": "Text/plain"});
Res.write (stdout);
Res.end ();
}

Exports.start = start;
Exports.upload = upload;

4 Index.js

var server = require ('./server ');
var route = require ('./route ');
var requesthandlers = require ('./requesthandlers ');
var handle ={}
handle["/"]= Requesthandlers.start;
handle["/start"]= Requesthandlers.start;
handle["/upload"]= requesthandlers.upload;

Server.start (Route.route,handle);

Parsing starts from Index.js the handle object stores the route string and method pointers

Server.js gets the path of the current user request to execute the path corresponding to the method actually performed is the method in Requesthandlers

Lesson six self-routing improvements, responding to the paths of different requests

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.