随堂练习:写一个基于koa的静态http模块并发布

重点在于理解koa中间件,扩展koa用法(不只是web框架,它还是Node.js模块,它可以做更多),并复习巩固上一节学的Node.js模块写法

练习koa用法,集成以下中间件

  1. "koa": "^2.0.0",
  2. "koa-compress": "^2.0.0",
  3. "koa-conditional-get": "^2.0.0",
  4. "koa-etag": "^3.0.0",
  5. "koa-favicon": "^2.0.0",
  6. "koa-static": "^3.0.0",

app.js

  1. var serve = require('koa-static');
  2. var Koa = require('koa');
  3. var app = new Koa();
  4. var favicon = require('koa-favicon');
  5. var compress = require('koa-compress')
  6. var conditional = require('koa-conditional-get');
  7. var etag = require('koa-etag');
  8. app.use(compress({
  9. filter: function (content_type) {
  10. return /text/i.test(content_type)
  11. },
  12. threshold: 2048,
  13. flush: require('zlib').Z_SYNC_FLUSH
  14. }))
  15. app.use(favicon(__dirname + '/public/favicon.ico'));
  16. // etag works together with conditional-get
  17. app.use(conditional());
  18. app.use(etag());
  19. // or use absolute paths
  20. app.use(serve(__dirname + '/dist'));
  21. app.listen(9090);
  22. console.log('listening on port 9090');

将上面代码改成bin模块并发布

static http server模块核心是koa-static模块

  1. // or use absolute paths
  2. app.use(serve(__dirname + '/dist'));

这里的目录即要作为static http server的目录,也就是我们需要动态的把它通过命令行配置

假设模块名称为stuq-koa-static-server

  1. $ npm i -g stuq-koa-static-server

通过内置命令`stuq-koa-static-server启动服务,

  1. $ stuq-koa-static-server .

如果没有指定目录,即当前目录

  1. $ stuq-koa-static-server

知识点

  • 获取当前目录
  • 命令行参数解析,推荐commander

更多

参考http-server模块,增加更多cli配置项

  1. $ http-server -h
  2. usage: http-server [path] [options]
  3. options:
  4. -p Port to use [8080]
  5. -a Address to use [0.0.0.0]
  6. -d Show directory listings [true]
  7. -i Display autoIndex [true]
  8. -e --ext Default file extension if none supplied [none]
  9. -s --silent Suppress log messages from output
  10. --cors[=headers] Enable CORS via the "Access-Control-Allow-Origin" header
  11. Optionally provide CORS headers list separated by commas
  12. -o [path] Open browser window after starting the server
  13. -c Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.
  14. To disable caching, use -c-1.
  15. -U --utc Use UTC time format in log messages.
  16. -P --proxy Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com
  17. -S --ssl Enable https.
  18. -C --cert Path to ssl cert file (default: cert.pem).
  19. -K --key Path to ssl key file (default: key.pem).
  20. -r --robots Respond to /robots.txt [User-agent: *\nDisallow: /]
  21. -h --help Print this list and exit.