Cli(command-line interface),中文是 命令行界面,简单来说就是可以通过命令行快速生成自己的项目模板等功能(比较熟悉的是vue-cli脚手架这些),把上述写的包做成Cli工具.

延续上一次的代码,这次现在readme.md里面先注释告诉用户又那些命令行的语句具体对应哪些功能

step1:README.md

# anydoor
Tiny NodeJS Static Web server
##安装 ```
npm i -g anydoor
```
##使用方法 ```
anydoor # 把当前文件夹作为静态资源服务器根目录
anydoor -p 3333 # 设置端口号为 3333 //手工自定义一个端口号
anydoor -h localhost # 设置host为localhost
anydoor -d /usr # 设置根目录为 /usr ```

Step2:安装yargs

yargs是什么? Yargs是通过解析参数和生成优雅的用户界面,帮助您构建交互式命令行工具。

安装yargs

npm i yargs

新建一个src/index.js,与app.js处于平级目录下,注意下面所定义的option是与defaultConfig的对应的内容

// process.argv1
// yargs
const yargs = require('yargs')
const Server = require('./app') const argv = yargs
.usage('anywhere [options]')
.option('p',{
alias:'port',
describe:'端口号',
default:9527
})
.option('h',{
alias:'hostname',
describe:'host',
default:'127.0.0.1'
})
.option('d',{
alias:'root',
describe:'root path',
default:process.cwd()
})
.version()
.alias('v','version')
.help()
.argv; const server = new Server(argv)
server.start()

app.js

const http = require('http');
const chalk = require('chalk')
const path = require('path')
const conf = require('./config/defaultConfig.js');
const route = require('./helper/route') class Server {
constructor(config){
this.conf = Object.assign({},conf,config)
}
start(){
const server = http.createServer((req,res)=>{
const url = req.url;
//拿到文件路径
const filePath = path.join(this.conf.root,req.url)
route(req,res,filePath,this.conf)
}); server.listen(this.conf.port,this.conf.hostname,()=>{
const addr = `http://${this.conf.hostname}:${this.conf.port}`;
console.log(`Server started at ${chalk.green(addr)}`);
})
}
} module.exports = Server

package.json添加main和bin两个选项

{
"devDependencies": {
"eslint": "^6.2.2"
},
"name":"anydoor",
"version":"0.01",
"main":"src/app.js",
"bin":{
"anydoor":"bin/anydoor"
}
}

新建anydoor/bin/anydoor

#! /usr/bin/env node

require('../src/index')

运行代码,成功启动服务,打开http://127.0.0.1:9999可以看到之前运行app.js的页面

--------------------------------------------------------------------------------------------------------------------

优化自动打开浏览器操作,下面修改之后运行之后会自动打开网页,非常方便

新建src/helper/openUrl.js

const {exec} = require('child_process')

module.exports = url=>{
switch(process.platform){
case 'darwin':
exec(`open ${url}`);
break
case 'win32':
exec(`start ${url}`);
break
}
}

src/app.js

const http = require('http');
const chalk = require('chalk')
const path = require('path')
const conf = require('./config/defaultConfig.js');
const route = require('./helper/route')
const openUrl = require('./helper/openUrl') class Server {
constructor(config){
this.conf = Object.assign({},conf,config)
}
start(){
const server = http.createServer((req,res)=>{
const url = req.url;
//拿到文件路径
const filePath = path.join(this.conf.root,req.url)
route(req,res,filePath,this.conf)
}); server.listen(this.conf.port,this.conf.hostname,()=>{
const addr = `http://${this.conf.hostname}:${this.conf.port}`;
console.log(`Server started at ${chalk.green(addr)}`);
openUrl(addr)
})
}
} module.exports = Server

NodeJS4-8静态资源服务器实战_构建cli工具的更多相关文章

  1. NodeJS4-7静态资源服务器实战_缓存

    浏览器发出一个请求,服务器解析出响应的结果返回给浏览器. 缓存是怎么工作的? 用户发起请求,浏览器检查本地是否存在缓存,如果第一次请求没有缓存,那就向服务器发起请求,服务器协商缓存的内容并且返回响应, ...

  2. NodeJS4-5静态资源服务器实战_优化压缩文件

    浏览器控制台看一下RequestHeader有一个Accept-Encoding,而RespondHeaders中也会有一个Content-Encoding和他进行对应. Accept-Encodin ...

  3. NodeJS4-9静态资源服务器实战_发到npm上

    登录->publish一下 ->上npm官网查看 -> 安装全局 //登录 npm login //推上去npm npm publish //全局安装 npm i -g 你的文件名

  4. NodeJS4-4静态资源服务器实战_优化引入模板引擎

    引入模板引擎(handlebars) cnpm i handlebars 结构大概是这样子的,新建模板dir.tpl文件和route.js dir.tpl <!DOCTYPE html> ...

  5. NodeJS4-3静态资源服务器实战_优化成近似同步写法

    实例3 上面有点回调,优化成近似同步的写法 route.js const fs =require('fs') const promisify = require('util').promisify; ...

  6. NodeJS4-2静态资源服务器实战_实现获取文件路径

    实例2 : 实现获取文件路径,判断是文件还是文件夹,如果是文件夹就显示里面的列表文件,如果是文件就显示里面的内容 defaultConfig.js module.exports={ root:proc ...

  7. NodeJS4-1静态资源服务器实战_实现访问获取里面的内容

    .gitignore 匹配模式前 / 代表项目根目录 匹配模式最后加 / 代表是目录 匹配模式前加 ! 代表取反 * 代表任意一个字符 ? 匹配任意一个字符 ** 匹配多级目录 统一代码风格配置可以用 ...

  8. NodeJS4-6静态资源服务器实战_range范围请求

    range范围请求:向服务器发起请求可以申明我想请求判断内容的范围,从多少个字节到多少个字节,一次要求把所有的内容拿回来,服务器在得到相应的请求之后,从拿到对应的文件,拿到对应的字节返回给客户端.要实 ...

  9. 使用Node.js搭建静态资源服务器

    对于Node.js新手,搭建一个静态资源服务器是个不错的锻炼,从最简单的返回文件或错误开始,渐进增强,还可以逐步加深对http的理解.那就开始吧,让我们的双手沾满网络请求! Note: 当然在项目中如 ...

随机推荐

  1. HashMap的源码学习以及性能分析

    HashMap的源码学习以及性能分析 一).Map接口的实现类 HashTable.HashMap.LinkedHashMap.TreeMap 二).HashMap和HashTable的区别 1).H ...

  2. canvas入门,就是这个feel!

    钙素 Canvas 是在HTML5中新增的标签用于在网页实时生成图像,并且可以操作图像内容,基本上它是一个可以用JavaScript操作的位图.也就是说我们将通过JS完成画图而不是css. canva ...

  3. Hadoop运行模式

    Hadoop运行模式 (1)本地模式(默认模式): 不需要启用单独进程,直接可以运行,测试和开发时使用. 即在一台机器上进行操作,仅为单机版. 本地运行Hadoop官方MapReduce案例 操作命令 ...

  4. docker容器访问宿主机的IP——以rocketmq管理工具为例

    在宿主机(MacOS系统)上运行了原生的RocketMQ服务,为了方便管理,需要以Docker方式运行RocketMQ的管理工具——rocketmq-console (项目地址:https://git ...

  5. Paramiko的SSH和SFTP使用

    目录 1. 概述 2. Paramiko的基本使用 2.1 SSHClient关键参数介绍 2.2 SSHClient常用示例 2.2.1 通过用户名和密码方式登陆: 2.2.2 通过用户名和密码方式 ...

  6. 2019 ICPC Asia Nanjing Regional K. Triangle

    题目:在直角坐标系中给定 p1,p2,p3构成三角形,给定p4可能在三角形边上也可能不在, 问能不能在三角形上找出p5,使得线段p4p5,平分三角形(p4必须在三角形上).不能则输出-1. 思路:四个 ...

  7. Spring(Bean)2

    <!-- util:list封装的心 --> <bean id="personList2" class="spring.beans.di.collect ...

  8. kubeadm 1.16+ 初始化后 Unable to update cni config: no valid networks found in /etc/cni/net.d

    问题描述: 在使用 kubeadm 工具初始化k8s后,并且安装了 flanneld 网络组建后,/var/log/messages 依旧报错, Unable to update cni config ...

  9. Spring Cloud Hoxton正式发布,Spring Boot 2.2 不再孤单

    距离Spring Boot 2.2.0的发布已经有一个半月左右时间,由于与之匹配的Spring Cloud版本一直没有Release,所以在这期间碰到不少读者咨询的问题都是由于Spring Boot和 ...

  10. ggplot2|玩转Manhattan图-你有被要求这么画吗?

    本文首发于“生信补给站”,ggplot2|玩转Manhattan图-你有被要求这么画吗?更多关于R语言,ggplot2绘图,生信分析的内容,敬请关注小号. Manhattan图算是GWAS分析的标配图 ...