NodeJS4-8静态资源服务器实战_构建cli工具
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工具的更多相关文章
- NodeJS4-7静态资源服务器实战_缓存
浏览器发出一个请求,服务器解析出响应的结果返回给浏览器. 缓存是怎么工作的? 用户发起请求,浏览器检查本地是否存在缓存,如果第一次请求没有缓存,那就向服务器发起请求,服务器协商缓存的内容并且返回响应, ...
- NodeJS4-5静态资源服务器实战_优化压缩文件
浏览器控制台看一下RequestHeader有一个Accept-Encoding,而RespondHeaders中也会有一个Content-Encoding和他进行对应. Accept-Encodin ...
- NodeJS4-9静态资源服务器实战_发到npm上
登录->publish一下 ->上npm官网查看 -> 安装全局 //登录 npm login //推上去npm npm publish //全局安装 npm i -g 你的文件名
- NodeJS4-4静态资源服务器实战_优化引入模板引擎
引入模板引擎(handlebars) cnpm i handlebars 结构大概是这样子的,新建模板dir.tpl文件和route.js dir.tpl <!DOCTYPE html> ...
- NodeJS4-3静态资源服务器实战_优化成近似同步写法
实例3 上面有点回调,优化成近似同步的写法 route.js const fs =require('fs') const promisify = require('util').promisify; ...
- NodeJS4-2静态资源服务器实战_实现获取文件路径
实例2 : 实现获取文件路径,判断是文件还是文件夹,如果是文件夹就显示里面的列表文件,如果是文件就显示里面的内容 defaultConfig.js module.exports={ root:proc ...
- NodeJS4-1静态资源服务器实战_实现访问获取里面的内容
.gitignore 匹配模式前 / 代表项目根目录 匹配模式最后加 / 代表是目录 匹配模式前加 ! 代表取反 * 代表任意一个字符 ? 匹配任意一个字符 ** 匹配多级目录 统一代码风格配置可以用 ...
- NodeJS4-6静态资源服务器实战_range范围请求
range范围请求:向服务器发起请求可以申明我想请求判断内容的范围,从多少个字节到多少个字节,一次要求把所有的内容拿回来,服务器在得到相应的请求之后,从拿到对应的文件,拿到对应的字节返回给客户端.要实 ...
- 使用Node.js搭建静态资源服务器
对于Node.js新手,搭建一个静态资源服务器是个不错的锻炼,从最简单的返回文件或错误开始,渐进增强,还可以逐步加深对http的理解.那就开始吧,让我们的双手沾满网络请求! Note: 当然在项目中如 ...
随机推荐
- MySQL 5.7 - 通过 BINLOG 恢复数据
日常开发,运维中,经常会出现误删数据的情况.误删数据的类型大致可分为以下几类: 使用 delete 误删行 使用 drop table 或 truncate table 误删表 使用 drop dat ...
- [Ubuntu篇] 在ubuntu上源码编译gtest,编写gtest-config.cmake并测试
本文首发于个人博客https://kezunlin.me/post/4a1427cf/,欢迎阅读! compile gtest on ubuntu 16.04 Guide compile gtest ...
- drf组件之jwt认证
drf组件之jwt认证模块 一.认证规则 全称:json web token 解释:加密字符串的原始数据是json,后台产生,通过web传输给前台存储 格式:三段式 - 头.载荷.签名 - 头和载荷才 ...
- 【论文阅读】Deep Mutual Learning
文章:Deep Mutual Learning 出自CVPR2017(18年最佳学生论文) 文章链接:https://arxiv.org/abs/1706.00384 代码链接:https://git ...
- Mysql操作之查询语句
查询语句: select 查询列表 from 表名 where 筛选条件; 去重:select distinct 查询列表...... 选择全部:* 起别名:select 查询列表 as 别名 fro ...
- Kafka use zkCli.sh to check topic offset on linux
> ./zkCli.sh -server zk1host:port,zk2host:port,zk3host:port >help ZooKeeper -server host:port ...
- Spring Cloud系列-Zuul网关集成JWT身份验证
前言 这两三年项目中一直在使用比较流行的spring cloud框架,也算有一定积累,打算有时间就整理一些干货与大家分享. 本次分享zuul网关集成jwt身份验证 业务背景 项目开发少不了身份认证,j ...
- 如何使用Git命令克隆仓库代码
今天我的电脑装了新系统,刚装了Git到电脑上,突然有一个大胆的想法,以后不适用可视化工具了. 要逐步锻炼我的命令的操作能力,不能太依赖可视化工具. 今天先记录一下如何使用git命令克隆仓库代码 git ...
- Too many open files的四种解决办法
[摘要] Too many open files有四种可能:一 单个进程打开文件句柄数过多,二 操作系统打开的文件句柄数过多,三 systemd对该进程进行了限制,四 inotify达到上限. 领导见 ...
- 基于webpack实现多html页面开发框架三 图片等文件路径替换、并输出到打包目录
一.解决什么问题 1.图片路径替换.并输出到打包目录 2.输出目录清理 二.需要安装的包 file-loader:html.css中图片路径替换,图片输出到打包目录:命令:npm ...