serve2 - 支持node.js的快速启动Web服务调试工具


MIT
跨平台
JavaScript

软件简介

与 Python 的 SimpleHTTPServer,Node.js 的 serve 不同,serve2
是一个支持动态文件的工具,前者们只支持静态文件,而serve2支持编写代码动态处理和返回http请求。

常常我们可能会有这样的需求场景:无论是在开发时还是尝试某个框架时,往往需要处理请求参数、Cookies、Http
headers等,这样简单的静态文件服务器便无法满足这种需求了。

于是serve2便应运而生了,基于Tj的serve开发,使用起来跟一般的静态文件服务器相同,执行一条命令即可。详细的用法介绍如下。

1. 下载安装

npm install -g serve2

2. 使用运行

λ serve2 --help


  Usage: serve2 [options] [dir]


  Options:


    -h, --help                output usage information
    -V, --version             output the version number
    -a, --auth <user>:<pass>  specify basic auth credentials
    -F, --format <fmt>        specify the log format string
    -p, --port <port>         specify the port [3000]
    -H, --hidden              enable hidden file serving
    -S, --no-stylus           disable stylus rendering
    -J, --no-jade             disable jade rendering
        --no-less             disable less css rendering
    -I, --no-icons            disable icons
    -L, --no-logs             disable request logging
    -D, --no-dirs             disable directory serving
    -f, --favicon <path>      serve the given favicon
    -M, --mocks <path>        mock files directory
        --cookies             add cookies parse support
    -C, --cors                allows cross origin access serving
        --compress            gzip or deflate the response
        --exec <cmd>          execute command on each request

3. 模拟后端

准备一个文件夹,如mock,然后启动的时候用-M参数指定。此目录下即为动态文件目录,可以模拟后端请求处理。如:

// mock/test.js  module.exports = function(req, res, next) { 
  var query = req.query; 
  var reqBody = req.body; 
  // ... res.end(query.hi);
}

则请求:

都将返回hello。js文件中的函数即是connect的中间件函数形式。

另外,也可以是json或其它文本文件, 甚至可以是目录:

4. 代理功能

当某个HTTP请求我们希望转发给服务器来处理时,可以在工作目录下创建一个文件名为proxylist.json,内容格式如下:

{
  "/": "http://www.baidu.com",
  "/t/180521": "https://www.v2ex.com" 
}

启动serve2后访问http://localhost:3000/,请求即会被proxy到baidu.com