http-server代码学习

echo off
cd /d %~dp0
java -Xmx512m -Xms128m -jar zookeeper-dev-​ZooInspector.jar.

npm install webpack-dev-server --save-dev
“scripts”: {
“start”: “webpack-dev-server --env development”,
“build”: “webpack --env production”
}
通过npm run start 或者 npm start来启动了
执行 npm install webpack webpack-cli -D ,
其中 -D 也就是 --save-dev,
如果是要作为生产环境的依赖则是 --save 即可

常用包

JS-SDK: 是微信公众平台向微信网页开发者提供的微信网页开发者工具包, 通过js-sdk我们可以高效的使用微信拍照,选图,语音,位置等手机系统的能力,并且可以使用微信分享,支付等功能
koa: 主要用来服务器初始化,接口调用已经数据返回
request:网络请求,对原生http request的封装
ejs模板: 微信的数据包是基于xml的,所以需要用ejs来把数据替换到xml中
lodash:常用的方法集,操作数据,类型判断
Heredoc: 将函数体内的多行注释提取出来
row-body: 用来获取http请求的可读流的实体的内容
sha1:项目中用到的hash算法
xml2js:将微信返回的xml数据转成js对象

作者:love_program
链接:https://www.jianshu.com/p/efc7dbc1590d
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
/*
 * 模板文件
 * 
 */
'use strict'

var ejs = require('ejs');
var heredoc = require('heredoc');

var tpl = heredoc(function(){/*
	<xml>
		<ToUserName><![CDATA[<%= toUserName %>]]></ToUserName>
		<FromUserName><![CDATA[<%= fromUserName %>]]></FromUserName>
		<CreateTime><%= createTime%></CreateTime>
		<MsgType><![CDATA[<%= msgType %>]]></MsgType>
		<% if(msgType ==='text') { %>
			<Content><![CDATA[<%= content %>]]></Content>
		<% }else if(msgType ==='image'){ %>
			<Image>
				<MediaId><![CDATA[<%= content.mediaId %>]]></MediaId>
			</Image>
		<% }else if(msgType ==='voice'){ %>
			<Voice>
				<MediaId><![CDATA[<%= content.mediaId %>]]></MediaId>
			</Voice>
		<% } else if(msgType ==='video'){ %>
			<Video>
				<MediaId><![CDATA[<%= content.mediaId %>]]></MediaId>
				<Title><![CDATA[<%= content.title %>]]></Title>
				<Description><![CDATA[<%= content.description %>]]></Description>
			</Video> 	
		<% } else if(msgType ==='music'){ %>
			<Music>
				<Title><![CDATA[<%= content.title %>]]></Title>
				<Description><![CDATA[<%= content.description %>]]></Description>
				<MusicUrl><![CDATA[<%= content.musicUrl %>]]></MusicUrl>
				<HQMusicUrl><![CDATA[<%= content.hqMusicUrl %>]]></HQMusicUrl>
				<ThumbMediaId><![CDATA[<%= content.thumbMediaId %>]]></ThumbMediaId>	
			</Music>
		<% } else if(msgType ==='news'){ %>
			<ArticleCount><%= content.length %></ArticleCount>
			<Articles>
				<% content.forEach(function(item){ %>
				<item>
					<Title><![CDATA[<%= item.title %>]]></Title> 
					<Description><![CDATA[<%= item.description %>]]></Description>
					<PicUrl><![CDATA[<%= item.picUrl %>]]></PicUrl>
					<Url><![CDATA[<%= item.url %>]]></Url>
				</item>
				<% }) %>
			</Articles>
		<% } %>	
	</xml>
*/});

var compiled = ejs.compile(tpl);

exports = module.exports = {
	compiled:compiled
};
#!/usr/bin/env node

'use strict';

var colors     = require('colors/safe'),
    os         = require('os'),
    httpServer = require('../lib/http-server'),
    portfinder = require('portfinder'),
    opener     = require('opener'),
    argv       = require('optimist')
      .boolean('cors')
      .argv;

var ifaces = os.networkInterfaces();

if (argv.h || argv.help) {
  console.log([
    'usage: http-server [path] [options]',
    '',
    'options:',
    '  -p           Port to use [8080]',
    '  -a           Address to use [0.0.0.0]',
    '  -d           Show directory listings [true]',
    '  -i           Display autoIndex [true]',
    '  -g --gzip    Serve gzip files when possible [false]',
    '  -e --ext     Default file extension if none supplied [none]',
    '  -s --silent  Suppress log messages from output',
    '  --cors[=headers]   Enable CORS via the "Access-Control-Allow-Origin" header',
    '                     Optionally provide CORS headers list separated by commas',
    '  -o [path]    Open browser window after starting the server',
    '  -c           Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.',
    '               To disable caching, use -c-1.',
    '  -U --utc     Use UTC time format in log messages.',
    '',
    '  -P --proxy   Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com',
    '',
    '  -S --ssl     Enable https.',
    '  -C --cert    Path to ssl cert file (default: cert.pem).',
    '  -K --key     Path to ssl key file (default: key.pem).',
    '',
    '  -r --robots  Respond to /robots.txt [User-agent: *\\nDisallow: /]',
    '  --no-dotfiles  Do not show dotfiles',
    '  -h --help    Print this list and exit.'
  ].join('\n'));
  process.exit();
}

var port = argv.p || parseInt(process.env.PORT, 10),
    host = argv.a || '0.0.0.0',
    ssl = !!argv.S || !!argv.ssl,
    proxy = argv.P || argv.proxy,
    utc = argv.U || argv.utc,
    logger;

if (!argv.s && !argv.silent) {
  logger = {
    info: console.log,
    request: function (req, res, error) {
      var date = utc ? new Date().toUTCString() : new Date();
      if (error) {
        logger.info(
          '[%s] "%s %s" Error (%s): "%s"',
          date, colors.red(req.method), colors.red(req.url),
          colors.red(error.status.toString()), colors.red(error.message)
        );
      }
      else {
        logger.info(
          '[%s] "%s %s" "%s"',
          date, colors.cyan(req.method), colors.cyan(req.url),
          req.headers['user-agent']
        );
      }
    }
  };
}
else if (colors) {
  logger = {
    info: function () {},
    request: function () {}
  };
}

if (!port) {
  portfinder.basePort = 8080;
  portfinder.getPort(function (err, port) {
    if (err) { throw err; }
    listen(port);
  });
}
else {
  listen(port);
}

function listen(port) {
  var options = {
    root: argv._[0],
    cache: argv.c,
    showDir: argv.d,
    autoIndex: argv.i,
    gzip: argv.g || argv.gzip,
    robots: argv.r || argv.robots,
    ext: argv.e || argv.ext,
    logFn: logger.request,
    proxy: proxy,
    showDotfiles: argv.dotfiles
  };

  if (argv.cors) {
    options.cors = true;
    if (typeof argv.cors === 'string') {
      options.corsHeaders = argv.cors;
    }
  }

  if (ssl) {
    options.https = {
      cert: argv.C || argv.cert || 'cert.pem',
      key: argv.K || argv.key || 'key.pem'
    };
  }

  var server = httpServer.createServer(options);
  server.listen(port, host, function () {
    var canonicalHost = host === '0.0.0.0' ? '127.0.0.1' : host,
        protocol      = ssl ? 'https://' : 'http://';

    logger.info([colors.yellow('Starting up http-server, serving '),
      colors.cyan(server.root),
      ssl ? (colors.yellow(' through') + colors.cyan(' https')) : '',
      colors.yellow('\nAvailable on:')
    ].join(''));

    if (argv.a && host !== '0.0.0.0') {
      logger.info(('  ' + protocol + canonicalHost + ':' + colors.green(port.toString())));
    }
    else {
      Object.keys(ifaces).forEach(function (dev) {
        ifaces[dev].forEach(function (details) {
          if (details.family === 'IPv4') {
            logger.info(('  ' + protocol + details.address + ':' + colors.green(port.toString())));
          }
        });
      });
    }

    if (typeof proxy === 'string') {
      logger.info('Unhandled requests will be served from: ' + proxy);
    }

    logger.info('Hit CTRL-C to stop the server');
    if (argv.o) {
      opener(
        protocol + canonicalHost + ':' + port,
        { command: argv.o !== true ? argv.o : null }
      );
    }
  });
}

if (process.platform === 'win32') {
  require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
  }).on('SIGINT', function () {
    process.emit('SIGINT');
  });
}

process.on('SIGINT', function () {
  logger.info(colors.red('http-server stopped.'));
  process.exit();
});

process.on('SIGTERM', function () {
  logger.info(colors.red('http-server stopped.'));
  process.exit();
});

388 
389 LiveServer.shutdown = function() {
390     var watcher = LiveServer.watcher;
391     if (watcher) {
392         watcher.close();
393     }
394     var server = LiveServer.server;
395     if (server)
396         server.close();
397 };
398 
399 module.exports = LiveServer;
?\<LiveServer\>

#!/usr/bin/env node
var path = require(‘path’);
var fs = require(‘fs’);
var assign = require(‘object-assign’);
var liveServer = require("./index");

liveServer.start(opts);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值