zoukankan      html  css  js  c++  java
  • Node 版 http 服务器

    怎么样快速起一个静态服务?

    可以使用 http-server

    # 安装
    $ npm install http-server -g
    
    # 开启
    $ http-server -c-1
    Starting up http-server, serving ./
    Available on:
      http://127.0.0.1:8080
      http://192.168.8.196:8080
    Hit CTRL-C to stop the server
    

    但用代码怎么写一个 http 服务器?

    废话不多说直接上代码

    //a node web server.
    var http = require("http");
    var url = require("url");
    var fs = require("fs");
    
    var mimeTypes = {
      css: { "Content-Type": "text/css" },
      js: { "Content-Type": "text/javascript" },
      png: { "Content-Type": "image/png" },
      jpg: { "Content-Type": "image/jpeg" },
      svg: { "Content-Type": "text/xml" },
    };
    
    function start() {
      function onRequest(request, response) {
        var params = url.parse(request.url, true),
          pathname = params.pathname;
        //静态资源服务器
        //fs.readFile(filename,[options],callback);
        if (pathname === "/") {
          fs.readFile(__dirname + "/index.html", function (err, file) {
            if (err) throw err;
            response.write(file, "binary");
            response.end();
          });
        } else {
          fs.readFile(__dirname + pathname, "binary", function (err, file) {
            if (err && err.code === "ENOENT") {
              response.writeHead(404, { "Content-Type": "text/plain" });
              response.write(err + "
    ");
              response.end();
            } else if (err) {
              response.writeHead(500, { "Content-Type": "text/plain" });
              response.write(err + "
    ");
              response.end();
            } else {
              var type = pathname.slice(pathname.lastIndexOf(".") + 1);
              if (mimeTypes[type]) {
                response.writeHead(200, mimeTypes[type]);
              }
              
              //有callback字段则为jsonp请求。
              if (params.query && params.query.callback) {
                var str = params.query.callback + "(" + file + ")";
                response.end(str);
              } else {
                response.end(file); //普通的json
              }
            }
          });
        }
      }
      var port = process.argv[2] || 3000;
      http.createServer(onRequest).listen(port);
      console.log("Server has started at port " + port);
    }
    start();
    
    

    还缺功能:

    • MIME 支持更加完善
    • 路径是目录默认读 index.html
    • 缓存支持
    • 内容 Accept-Encoding 编码
  • 相关阅读:
    js replace替换 忽略大小写问题
    Spring security实现国际化问题
    Mac 的mysql5.7没有配置文件,如何解决only_full_group_by 问题
    java设计模式学习
    synchronized的锁问题
    理解java的三种代理模式
    [acm]HDOJ 2059 龟兔赛跑
    [acm]HDOJ 2673 shǎ崽 OrOrOrOrz
    [acm]HDOJ 1200 To and Fro
    [acm]HDOJ 2064 汉诺塔III
  • 原文地址:https://www.cnblogs.com/everlose/p/12840121.html
Copyright © 2011-2022 走看看