npm script 工作流(十三)自动化运维
版本管理
package.json 中添加如下 scripts
+ "release:patch": "npm version patch && git push && git push --tags",
+ "release:minor": "npm version minor && git push && git push --tags",
+ "release:major": "npm version major && git push && git push --tags",
"precommit": "lint-staged",
这 3 条命令遵循 semver 的版本号规范来方便你管理版本,patch 是更新补丁版本,minor 是更新小版本,major 是更新大版本。在必要的时候,可以通过运行 npm run version:patch 来升补丁版本
image.png
scripts 目录下新增 bump.sh
1、添加权限:chmod a+x scripts/bump.sh
2、内容如下:
#!/usr/bin/env bash
# get major/minor/patch version to change
version=`cat package.json| grep version | grep -v release | awk -F\" '{print $4}'`
components=($(echo $version | tr '.' '\n'))
major=${components[0]}
minor=${components[1]}
patch=${components[2]}
release='patch';
# decide which version to increment
if [ $patch -ge 9 ]; then
if [ $minor -ge 9 ]; then
release='major'
else
release='minor'
fi
else
release='patch'
fi
echo "major=$major, minor=$minor, patch=$patch, release=$release"
# upgrade version
npm run release:$release
3、package.json添加
```patch
"release:major": "npm version major && git push && git push --tags",
+ "bump": "scripty",
"precommit": "lint-staged",
4、运行 npm run bump
image.png
服务进程和日志管理
项目中引入 express 和 morgan (morgan 使用来记录用户的访问日志)
安装
npm i express morgan -D
# npm install express morgan --save-dev
# yarn add express morgan -D
创建server.js
const express = require('express');
const morgan = require('morgan');
const app = express();
const port = process.env.PORT || 8080;
app.use(express.static('./dist'));
app.use(morgan('combined'));
app.listen(port, err => {
if (err) {
console.error('server start error', err); // eslint-disable-line
process.exit(1);
}
console.log(`server started at port ${port}`); // eslint-disable-line
});
准备日志目录(logs)
mkdir logs
touch logs/.gitkeep
git add logs/.gitkeep
git commit -m 'add logs folder'
添加忽略
.gitignore
安装和配置 pm2
npm i pm2 -D
# npm install pm2 --save-dev
# yarn add pm2 -D
pm2.json
{
"apps": [
{
"name": "npm-script-workflow",
"script": "./server.js",
"out_file": "./logs/stdout.log",
"error_file": "./logs/stderr.log",
"log_date_format": "YYYY-MM-DD HH:mm:ss",
"instances": 0,
"exec_mode": "cluster",
"max_memory_restart": "800M",
"merge_logs": true,
"env": {
"NODE_ENV": "production",
"PORT": 8080,
}
}
]
}
置指定了服务脚本为 server.js,日志输出文件路径,日志时间格式,进程数量 = CPU 核数,启动方式为 cluster,以及两个环境变量。
配置服务部署命令
"release:major": "npm version major && git push && git push --tags",
+ "predeploy": "yarn && npm run build",
+ "deploy": "pm2 restart pm2.json",
"bump": "scripty",
npm run deploy
image.png
配置日志查看命令
+ "logs": "tail -f logs/*",
"bump": "scripty",
运行:npm run logs
image.png
发表评论 (审核通过后显示评论):