美文网首页
nodejs---web静态服务器

nodejs---web静态服务器

作者: 一直玩编程 | 来源:发表于2016-08-10 13:24 被阅读268次

    server.js

    'use strict';
    
    
    const http = require('http');
    const url = require('url');
    const fs = require('fs');
    const path = require('path');
    
    
    //default config
    let config = {
      ip: '0.0.0.0',
      port: 4000,
      defaultDirectory: process.cwd() + '/public'
    }
    
    
    
    
    
    const server = http.createServer();
    
    
    
    initConfig();
    
    
    // listen request
    server.on('request', (req, res) => {
      let urlpath = url.parse(req.url);
      let pathname = decodeURIComponent(urlpath.pathname);
    
      //default index.html
      if (pathname === "/") pathname += "index.html";
      //get full path
      let fullPath = path.join(config.defaultDirectory, pathname);
      fs.exists(fullPath, (exists) => {
        if (exists) {
          fs.readFile(fullPath, (err, data) => {
            if (err) {
              res.statusCode = 500;
              res.statusMessage = 'Internal Server Error';
              res.write('Internal Server Error');
              res.end();
    
            } else {
              res.writeHead(200, {
                'content-type': getMimeType(fullPath)
              });
              res.write(data);
              res.end();
            }
          })
        } else {
          res.statusCode = 404;
          res.statusMessage = 'Not found';
          res.write('file Not found');
          res.end();
        }
      })
    
    
      // get MimiType by file path
      function getMimeType(file) {
        let i = file.lastIndexOf("."),
          ext = (i === -1) ? "default" : file.substr(i),
          mimeTypes = {
            ".bmp": "image/bmp",
            ".css": "text/css",
            ".gif": "image/gif",
            ".htm": "text/html",
            ".html": "text/html",
            ".jpg": "image/jpeg",
            ".jpeg": "image/jpeg",
            ".js": "application/javascript",
            ".json": "application/json",
            ".otf": "font/opentype",
            ".png": "image/png",
            ".text": "text/plain",
            "default": "application/octet-stream"
          };
        return mimeTypes[ext.toLowerCase()];
      }
    
    
    })
    
    
    // get start-up parameters
    //but process.argv is 2 start
    function initConfig() {
      let array = process.argv;
      for (var i = 2; i < array.length; i += 2) {
        switch (array[i]) {
          case '-d':
            config.defaultDirectory = (array[i + 1] === undefined ? config.defaultDirectory : array[i + 1]);
            break;
          case '-p':
            config.port = (array[i + 1] === undefined ? config.port : array[i + 1]);
            break;
          case '-h':
            config.ip = (array[i + 1] === undefined ? config.ip : array[i + 1]);
            break;
          case '-help':
            usage();
            process.exit();
            break;
          default:
            break;
        }
      }
    }
    
    /*
    
     usage
     print help
    
    */
    
    function usage() {
      let SWITCHES = [
        '-d appoint this directory to listen to',
        '-p port to listen on',
        '-h this ip to setting',
        '-help show this help screen'
      ];
      SWITCHES.forEach(elem => {
        // body...
          process.stdout.write(elem+"\n");
        //console.log(elem);
      });
    
    
    }
    
    
    
    //start listen
    server.listen(config.port, config.ip, () => {
    
      console.log(`${config.ip}:${config.port} start`);
    
    })
    

    使用方法

    node server.js

    参数
    * -d 目录 默认 public

    • -p 端口 默认 4000
    • h ip 默认 0.0.0.0
    • -help 帮助

    例如
    node server.js -d ./public01

    Web最新资讯,请关注我的微信公众号“一起玩前端”或扫描二维码关注.

    qrcode_for_gh_7a765c30aeb7_258.jpg

    相关文章

      网友评论

          本文标题:nodejs---web静态服务器

          本文链接:https://www.haomeiwen.com/subject/qoqjsttx.html