ITPub博客

首页 > 应用开发 > IT综合 > Node.js+Socket.io消息中心实施之五 消息中心的实现(3)

Node.js+Socket.io消息中心实施之五 消息中心的实现(3)

原创 IT综合 作者:百联达 时间:2014-07-14 15:36:11 0 删除 编辑
Http请求处理

1.requestHandlers.js  http请求处理类

var exec = require("child_process").exec;
var querystring = require("querystring");
var url = require("url");
var fs = require("fs");
var formidable = require("/usr/local/lib/node_modules/formidable");

function start(response,request) {
 console.log("Request handler 'start' was called.");
 
 /*exec("ls -lah", function (error, stdout, stderr)
  {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write(stdout);
  response.end();
  });*/

        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write('

Hello! Try the Socket.io Test

');
        response.end();

 }

function index(response,request)
{
 var path = url.parse(request.url).pathname;


     fs.readFile(__dirname + path, function(err, data){
        if (err)
  {
   response.writeHead(404);
         response.write('404');
         response.end();

  }
        response.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'});
        response.write(data, 'utf8');
        response.end();
        });


}

function upload(response,request) {
 console.log("Request handler 'upload' was called.");
 
 var form = new formidable.IncomingForm();
 console.log("about to parse");
 form.parse(request, function(error, fields, files) {
  console.log("parsing done");
  fs.renameSync(files.upload.path, "/data/nodejs/tmp/test.png");
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("received image:
");

  response.write("");
  response.end(); });
 }


function show(response, request) {
 
 console.log("Request handler 'show' was called.");
 fs.readFile("./tmp/test.png", "binary", function(error, file) {
  if(error) {
   response.writeHead(500, {"Content-Type": "text/plain"});
   response.write(error + "\n");
   response.end(); }
   else {
    response.writeHead(200, {"Content-Type": "image/png"});
    response.write(file, "binary");
    response.end(); } });
    
}
 
 
exports.start = start;
exports.upload = upload;
exports.show = show;
exports.index = index;


2.router.js  Http请求路由类

function route(handle,pathname,response,request) {
 
 console.log("About to route a request for " + pathname);

 if(typeof handle[pathname] == 'function')
 {
   handle[pathname](response,request);
 }
 else
 {
  console.log("No request handler found for "+pathname);
  response.writeHead(404, {"Content-Type": "text/plain"});
  response.write("404 Not found");
  response.end();
 }
 }
 

exports.route = route;

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28624388/viewspace-1218475/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
15年以上互联网经验,先后从事过制造业,证券业,物业行业和物流行业信息系统和互联网产品的设计落地实施,8年系统架构经验。最近关注企业数字化转型、财务数字化服务共享、大语言模型、Kubernetes微服务架构和Istio微服务治理框架。

注册时间:2013-02-05

  • 博文量
    332
  • 访问量
    1265635