zoukankan      html  css  js  c++  java
  • nodejs的简单服务器程序

    下面是参考<Jquery、Jquery UI 及Jquery Mobile>一书中的nodej服务器程序

    var http = require('http'),
        url = require('url'),
        fs = require('fs');
    http.createServer(function (req, res) {
      var reqData = {
            url: url.parse(req.url, true),
            method: req.method,
            headers: req.headers },
            path = reqData.url.pathname;
    
      if(path.match(/^/[0-9a-z-]+.(html)|(json)|(xml)$/))
        fs.readFile('.' + path, function (err, data) {
          if (err) {
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end('not found');
          }
          else {
           if(path.split('.')[1] == 'html')
               res.writeHead(200, {'Content-Type': 'text/html'});
           else if(path.split('.')[1] == 'xml')
               res.writeHead(200, {'Content-Type': 'application/xml'});
           else 
             res.writeHead(200, {'Content-Type': 'application/json'});
           res.end(data);
          }   
        });
      else if(path == '/return-http-headers') {
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify(reqData));
      }
      else if(path == '/sleep') {
        var endTime = new Date().getTime() + 2000;
        while (new Date().getTime() < endTime);
        res.writeHead(500, {'Content-Type': 'text/plain'});
        res.end('slow response');
      }
      else if(path == '/validate') {
        var keys = [];
        for(var key in reqData.url.query) {
            if(reqData.url.query[key] == '')
                keys.push(key);
        }
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify(keys));
      }
      else if(path == '/redirect') {
        res.writeHead(302, {
          'Location': '/test-values.json' });
        res.end();    
      }
      else if(path == '/fail-on-purpose') {
        res.writeHead(500, {'Content-Type': 'text/plain'});
        res.end('unexpected" error');
      }
      else {
       res.writeHead(404, {'Content-Type': 'text/plain'});
       res.end('not found');
      }
    }).listen(1337, "localhost");
    console.log('Server running at http://localhost:1337/');
  • 相关阅读:
    8、linux-wc命令 打印出文件中字符行数
    7、linux-排序命令 sort
    6、linux-查看文件 ls
    5、linux-查找命令 grep
    4、linux-文档编辑命令:vi
    第二次作业
    JSP 第一次作业 开发环境搭建
    第十一次作业—安卓课程设计报告
    第十次作业—listview+sqlite 购物车
    第九次作业sharedpreferences实现数据存储-记住账号密码
  • 原文地址:https://www.cnblogs.com/scnuwangjie/p/4965940.html
Copyright © 2011-2022 走看看