think-cli

// 查看 think-cli 的版本号
thinkjs -V

// 查看 think-cli 帮助
thinkjs -h

// 查看具体命令的使用帮助
thinkjs help [command-name]
thinkjs [command-name] -h

// 列出可用的官方模板
thinkjs list

// 创建项目
thinkjs new project-name [template-name]

// 创建 controller 文件
thinkjs controller controller-name [module-name]

// 通过 -r 创建 RESTful Controller 文件
thinkjs controller controller-name [module-name] -r

// 创建 model 文件
thinkjs model model-name [module-name]

// 创建 service 文件
thinkjs service service-name [module-name]

// 创建 middleware 文件
thinkjs middleware middleware-name [module-name]

// 创建 adapter 文件
thinkjs adapter adapter-name [module-name]

// 创建项目模块
thinkjs module module-name

// 将最新的项目模板同步到本地缓存目录
thinkjs sync

// 清除项目模板缓存
thinkjs clean

npm

npm -v 查看 npm 的版本
npm help 查看某条命令的详细帮助
npm init 在项目中引导创建一个package.json文件
npm install [-g] [--save] 安装模块
npm uninstall 卸载模块
npm start 启动模块
npm test 测试模块
npm run 运行脚本
npm update 更新模块
npm ls 查看安装的模块
npm root 查看包的安装路径
npm version 查看模块版本

Config

// 使用配置,分别在 ctx 、controller 和其他情况下
ctx.config(key)
this.config(key)
think.config(key)

// 动态设置配置
think.config(key, value)

// 多环境配置
// 多环境配置文件格式为:[name].[env].js,如:config.development.js,config.production.js
// 目前只有 config.js 和 adapter.js 是支持不同环境配置文件的

Route

路由配置
配置文件路径
src/config/middleware.js
src/common/config/middleware.js

配置参数:
defaultModule 默认模块
defaultController 默认控制器
defaultAction 默认操作
prefix 默认去除的 pathname 前缀
suffix 默认去除的 pathname 后缀
denyModules 禁止访问的模块列表

自定义路由规则
自定义路由规则配置文件路径
src/config/router.js
src/common/config/router.js

自定义路由规则:
格式:[match, pathname, method, options]
match 匹配规则,字符串或者正则
pathname 解析后对应的 module controller、action
method 对应的请求方法
options 额外的选项

字符串路由
['/user/:name', 'user']
通过 this.get("name") 获取

正则路由
[//user/(w+)/, 'user?name=:1']

重定向
['/usersettings', '/user/setting', 'redirect', {statusCode: 301}]

RESTful 路由
[//user(?:/(d+))?/, 'user?id=:1', 'rest']
rest 表示为 REST API

Log

think.logger.debug('debug message');
think.logger.info('info message');
think.logger.warn('warning');
think.logger.error(new Error('error'));

Model

Cache

// 获取缓存
await ctx.cache('name')
await this.cache('name')
await think.cache('name')

// 设置缓存
await this.cache('name', 'value');

// 删除缓存
await this.cache('name', null);

Cookie

// 在 ctx、controller、logic 中,提供了 cookie 方法来操作 cookie。
// 获取 cookie
this.cookie('theme')

// 设置 cookie
this.cookie('theme', 'gray');
// 设定 cookie 时指定额外的配置
this.cookie('theme', 'yellow', {
maxAge: 10 * 1000,
path: '/theme'
})

// 删除 cookie
this.cookie('theme', null)
this.cookie('theme', null, {
domain: '',
path: ''
})

DEBUG

// 查看配置文件的详细加载情况
DEBUG=think-loader-config-* npm start

// 查看路由解析调试信息
DEBUG=think-router npm start

Session

// 读取 session
await this.session('name')

// 设置 session
await this.session('name', 'value')

// 删除 session
await this.session(null)

Logic

// 请求类型校验
this.allowMethods = 'post'
this.allowMethods = 'get,post'

//

支持的校验类型
// 字段必填,默认 false
// undefined、空字符串 、null、NaN 在 required: true 时校验不通过
required

// 当另一个项的值为某些值其中一项时,该项必填
requiredIf

View

// 单条赋值
this.assign('title', 'thinkjs');

// 多条赋值
this.assign({
title: 'thinkjs',
name: 'test'
});

// 获取之前赋过的值
this.assign('title');

// 获取所有赋的值
this.assign();

// 获取渲染后的内容
await this.render();
await this.render('doc');
await this.render('doc/detail');

// 渲染并输出内容
await this.display();
await this.display('doc');
await this.display('doc/detail');

Nunjucks

think

// Koa Application 对象的实例
think.app
// 等同于 think 对象
think.app.think
// 模块列表,单模块项目下为空数组
think.app.modules
// 存放项目下的 controller 文件,便于后续快速调用
think.app.controllers
// 存放项目下的 logic 文件
think.app.logics
// 存放项目下的模型文件
think.app.models
// 存放 service 文件
think.app.services
// 存放自定义路由配置
think.app.routers
// 存放校验配置
think.app.validators
// 创建 HTTP 服务后的 server 对象
think.app.server

// 项目的根目录
think.ROOT_PATH

// APP 根目录
think.APP_PATH

// 当前运行环境,等同于 think.app.env
think.env

// 当前 ThinkJS 的版本号
think.version

// 读取或者设置配置
think.config(name, value, m)

// 控制器基类,其他控制器类继承该类
think.Controller

// Logic 基类,继承自 think.Controller
think.Logic

// Service 基类
think.Service

// 实例化 Service 类
think.service(name, m, ...args)

// 服务启动之前要注册执行的函数
think.beforeStartServer(fn)

// 判断是否是数组
think.isArray(array)

// 判断输入是否是布尔值
think.isBoolean(boolean)

// 判断输入的是否是整数
think.isInt(any)

// 判断输入是 null
think.isNull(any)

// 判断输入是 null 或者 undefined
think.isNullOrUndefined(any)

// 判断输入是否是数字
think.isNumber(number)

// 判断输入是否是字符串
think.isString(str)

// 判断输入是不是一个字符串类型的数字
think.isNumberString(str)

// 判断输入是否是 Symbol 类型
think.isSymbol(any)

// 判断输入是否是 undefined
think.isUndefined(any)

// 判断对象是否为空
// undefined, null ,'', NaN, [], {}, 0, false 为 true,其他为 false。
think.isEmpty(any)

// 判断是否是真正的空
// undefined、null、''、NaN 为 true,其他为 false
think.isTrueEmpty(any)

// 判断输入是否是正则对象
think.isRegExp(reg)

// 判断输入是否是日期对象
think.isDate(date)

// 判断输入是否是Error类型
think.isError(error)

// 判断输入是否是函数类型
think.isFunction(any)

// 判断一个输入是否为 Object
think.isObject(obj)

// 判断输入是否是原始类型
// 包含:null、string、boolean、number、symbol、undefined
think.isPrimitive(any)

// 判断一个字符串是否是 ip 地址
think.isIP(ip)

// 判断一个字符串是否是 IP v4 地址
think.isIPv4(ip)

// 判断一个字符串是否是 IP v6 地址
think.isIPv6(ip)

// 判断输入是否是一个Buffer对象
think.isBuffer(buffer)

// 判断当前进程是否为主进程
think.isMaster

// 把一个 callback 函数包装 成Promise
think.promisify(fn, receiver)

// 将 setTimeout 包装为 Promise
think.timeout(num)

// 生成一个 Deferred 对象
think.defer()

// 深拷贝对象
think.extend(target,...any)

// 忽略对象中的某些属性,返回新的对象
think.omit(obj, props)

// 把字符串转成驼峰表示法
think.camelCase(str)

// 把驼峰写法转化为蛇形写法
think.snakeCase(str)

// 对字符串进行 HTML 转义
// 转义 <、>、"、' 字符
think.escapeHtml(str)

// 计算字符串的 md5 值
think.md5(str)

// 返回一个格式化日期
think.datetime(date, format)

// 把一个语义化的时间转成毫秒
think.ms(str)

// 生成 uuid 字符串
think.uuid(version)

// 检测路径是否存在
think.isExist(path)

// 检测是否是一个文件路径
think.isFile(filepath)

// 检测是否是一个文件夹路径
think.isDirectory(filepath)

// 改变文件或文件夹的权限
think.chmod(path, mode)

// 创建文件夹
think.mkdir(path, mode)

// 获取文件夹下的所有文件
think.getdirFiles(dir, prefix)

// 删除文件夹和文件夹下的文件
think.rmdir(path, reserve)

Context

Koa 内置 API
// Node 的 request 对象
ctx.req

// Node 的 response 对象
ctx.res

// Koa 的 Request 对象
ctx.request

// Koa 的 Response 对象
ctx.response

// 在中间件之间传递信息以及将信息发送给模板时,推荐的命名空间
// 这样后续在 controller 里可以通过 this.ctx.state.user 来获取对应的值
ctx.state

// 应用实例引用,等同于 think.app
ctx.app

// 获取所有的 header 信息,等同于 ctx.request.header
ctx.header

// 获取所有的 header 信息,等同于 ctx.header
ctx.headers

// 获取请求类型,大写
ctx.method

// 获取请求地址
ctx.url

// 获取原始的请求 URL
ctx.originalUrl

// 获取请求源 URL,包括协议和主机
// http://example.com
ctx.origin

// 获取请求完整的 URL,包括协议、主机和 url
// http://example.com/foo/bar?q=1
ctx.href

// 获取请求路径名
ctx.path

// 获取解析后的查询参数对象
ctx.query

// 获取原始查询字符串,不带问号
ctx.querystring

// 获取原始查询字符串,带问号
ctx.search

// 获取主机
ctx.host

// 获取主机名
ctx.hostname

// 获取请求头部 Content-Type 的值,不包括字符集
// "image/png"
ctx.type

// 获取请求的字符集
// "utf-8"
ctx.charset

// 获取请求的协议类型
ctx.protocol

// 检查该请求是否使用 https
ctx.secure

// 获取客户端请求的地址
ctx.ip

// 获取响应体
ctx.body

// 获取响应头部 Content-Length 的长度
ctx.length

// 返回请求头部指定字段的值
ctx.get(field)

// 获取响应状态码
ctx.status

// 对指定的 url 进行 302跳转
ctx.redirect(url, [alt])

// 将响应头 Content-Disposition 设置为 "attachment" 通知客户端可以进行下载
ctx.attachment([filename])

// 通过一个对象设置多个响应头部字段
ctx.set(fields)

框架扩展 API
// 路由解析后的模块名, 单模块下为空
ctx.module

// 路由解析后的控制器名
ctx.controller

// 路由解析后的操作名
ctx.action

// 获取用户的 userAgent
ctx.userAgent

// 判断当前请求类型是否是 GET
ctx.isGet

// 判断当前请求类型是否是 POST
ctx.isPost

// 判断当前请求类型是否是 CLI
ctx.isCli

// 获取请求的 referer
ctx.referer(onlyHost)

// 判断当前请求类型与 method 是否相同
ctx.isMethod(method)

// 判断是否是指定类型的 ajax 请求
ctx.isAjax(method)

// 判断是否是 jsonp 请求
ctx.isJsonp(callbackField)

// 输出 jsonp 格式的数据
ctx.jsonp(data, callbackField)

// 输出 json 格式的数据
ctx.json(data)

// 输出带有 errno 和 errmsg 格式的数据
ctx.success(data, message)

// 输出带有 errno、errmsg 和 data 格式的数据
ctx.fail(errno, errmsg, data)

// 获取、设置配置项
ctx.config(name, value, m)

// 获取、设置 URL 上的参数值
ctx.param(name, value)

// 获取、设置 POST 数据
ctx.post(name, value)

// 获取、设置文件数据
ctx.file(name, value)

// 获取、设置 Cookie 值
ctx.cookie(name, value, options)

// 获取 service
ctx.service(name, m, ...args)

// 下载文件
ctx.download(filepath, filename)

标签: Node.js, ThinkJS, Koa