Getting Node.js Apps Production Ready
部署程序需要知道的方面:
- Environment variables
- Express.js in production
- Socket.IO in production(在线文章缺失这章)
- Error handling
- Node.js domains for error handling
- Multithreading with Cluster
- Multithreading with Cluster2
- Event logging and monitoring
- Building tasks with Grunt
- Locking dependencies
- Git for version control and deployments
- Running tests in Cloud with TravisCI
Environment Variables
在部署到产品环境之前,需要准备好代码。私人的信息不要放入版本控制系统。
敏感信息如API keys,密码,数据库的URIs最好储存在环境变量内。不要放到源码中。
Node.js可以容易的存取这些环境变量:
console.log (process.env.NODE_ENV,
process.env.API_KEY,
process.env.DB_PASSWORD)
然后,在程序开始前, 设置这些变量:
$ NODE_ENV=test API_KEY=XYZ DB_PASSWORD=ABC node envvar.js
一般,这些环境变量设置是部署的一部分,或者operations setup。
下一章,我们在server内处理这些变量。
Express.js in Production
使用判断语法来检测NODE_ENV变量的值,根据值来使用不同层次的服务logs。
比如开发阶段,我们需要大量的信息,但是在产品阶段,stack和exceptions可能会导致攻击,所以:
const errorHandler = require('errorhandler')
if (process.env.NODE_ENV === 'development') {
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}))
} else if (process.env.NODE_ENV === 'production') {
app.use(errorHandler())
}
process.env.NODE_ENV作为环境变量,可以在terminal(bash, zsh或者其他)设置。
环境变量的语法规则是:
KEY=VALUE
//或者在整个shell session时使用 export KEY=VALUE //例子
$ NODE_ENV=production node app.js
备注:
不是很立即本章给的代码。(https://github.com/azat-co/practicalnode/blob/master/chapter10/chapter10.md)
Error handler
Multithreading with Cluster
核心模块Cluster可以多线程处理系统load。
Event Logging and Monitoring
- Monitor via dashboard and health statuses (monitoring and REPL)
- Analyze postmortems after the events have happened (Winston and Papertrail)
Building Tasks with Grunt
It performs compilations, minifications, linting, unit testing, and other important tasks for automation.
A Brief on Webpack
和Grunt的功能类似。
module.exports = {
entry: "./jsx/app.jsx",
output: {
path: __dirname + '/js',
filename: "bundle.js"
},
// ... More configurations
}
见之前的博客:
webpack基础概念
https://www.cnblogs.com/chentianwei/p/9877570.html
Locking Dependencies
使用^或者*, 或者在package.json内让version field空着,都会导致下载更高的版本,当你或谁执行npm install。
一个解决方案是,commit node_modules to git
因为即使我们锁定包A在我们的package.json内,很可能A内有一个*或者版本的范围。因此一旦更新,这个A module可能break system。
Commiting模块到你的版本控制系统。
Git for Version Control and Deployments
安装
生成SSH key.
创建本地仓库:
Running Tests in Cloud with TravisCI
使用云端跑测试。有不少选择。