Date post: | 02-Dec-2014 |
Category: |
Technology |
Upload: | shawn-meng |
View: | 2,349 times |
Download: | 0 times |
我们的场景
•奉行价值投资理念的互联网金融信息服务公司• 股票的价格资料查询、研究分析和新闻报道• 给投资者提供最好的互动交流体验
我们眼中的前后端• 后端工程师与机器打交道• 完善的 Web 服务接口
• 接口的响应速度• 可用性• 可扩展性• ……
我们眼中的前后端
• 前端工程师与用户打交道• 涉及到服务器的 Web 优化策略
• 根据需求来决定HTML的渲染位置
我们直接用node.js来开发Web应用吗?
Node的HTTP模块
• 没有内置的cookie parser
• 没有内置的session支持
• 没有内置的路由分发模块• 没有内置的模板系统
Express
• Express by TJ Holowaychuk is an extremely popular web framework. It’s fast, simple, and easy to learn, and even better — it’s actively maintained!
——Alex Young from dailyjs.com
安装与创建demo
• git clone https://github.com/visionmedia/express.git
• npm install express
• node bin/express /tmp/foo && cd /tmp/foo
• npm install -d
var express = require('express');var app = express.createServer();
app.configure(function(){ app.use(express.bodyParser()); app.use(express.cookieParser()); app.use(express.session({ secret: 'your secret here' })); app.use(app.router);});
app.get('/', function(req, res){ res.render('Hello world');});
app.listen(3000);
Routesfunction loadUser(req, res, next) { var user = users[req.params.id]; if (user) { req.user = user; next(); } else { next(new Error('Failed to load user ' + req.params.id)); }}app.get('/user/:id', loadUser, function(req, res){ res.send('Viewing user ' + req.user.name);});
Cookie & Sessionfunction loadUser(req, res, next) { if (req.session.user) { return req.session.user; } var user = users[req.params.id]; if (user) { req.session.user = req.user = user; next(); } else { next(new Error('Failed to load user ' + req.params.id)); }}
Do HTTP request
• 自己用node的http模块
• 社区里封装好的库
request
• git clone https://github.com/mikeal/request.git
• npm install request
var request = require('request'); request( {uri:'http://www.google.com'}, function (error, response, body) { if (!error && response.statusCode == 200) { sys.puts(body) // Print the google web page. } })
Template Engines
• Haml
• Jade
• EJS
• CoffeeKup
• ……
Mustache
• Logic-less templates
• 在浏览器端使用很方便
• 浏览器和服务器共用模板
Stache
• Stache is mustache.js for your node express apps
app.set('view engine', 'mustache')app.register(".mustache", require('stache'));
app.get('/', function (req, res) { res.render("index", { locals: { title: "Title content", body: "Page content" }, partials: { heading: '<title>{{title}}</title>' } });});
<!-- index.mustache --><html><head> {{>heading}} </head><body> {{{body}}} </body></html>
app.get('/', function (req, res) { res.render("index", { locals: { title: "Title content", body: "Page content" }, partials: { heading: '<title>{{title}}</title>' } });});
<!-- index.mustache --><html><head> {{>heading}} </head><body> {{{body}}} </body></html>
<html><head> <title>Title content</title> </head><body> Page content </body></html>
然后呢?
然后呢?
BUG呗
然后呢?
BUG呗
我们的程序不可能保证万无一失,肯定有些没有处理的错误。这就让很多人觉得NodeJS不稳定,容易产生很多故障。
然后呢?
BUG呗
我们的程序不可能保证万无一失,肯定有些没有处理的错误。这就让很多人觉得NodeJS不稳定,容易产生很多故障。
但是我们要避免!
原因:只要程序中有错,node就会退出。解决方案:
node自己退出了
原因:只要程序中有错,node就会退出。解决方案:
1. 使用 try{…} catch(error){…} 来执行容易出错的代码段
node自己退出了
原因:只要程序中有错,node就会退出。解决方案:
1. 使用 try{…} catch(error){…} 来执行容易出错的代码段
2. process.on('uncaughtException', function (err) {//doSomething}
node自己退出了
访问没有响应app.get("/err", function(req, res, next){ fs.readFile('file', function(err, data){ });})
if (err) {throw err;}
访问没有响应app.get("/err", function(req, res, next){ fs.readFile('file', function(err, data){ });})
if (err) {next(err);}
访问没有响应app.get("/err", function(req, res, next){ fs.readFile('file', function(err, data){ });})
if (err) {next(err);}
app.error(function(err, req, res){ console.err(err.stack); res.render("500.html", { locals: { page_title: '500_我的首页_i美股' }, status: 500 }); });
让express稳定的tips
• 容易出错的代码片段一定要try{}catch(e){}
• 在routes的callback里得到error时不能throw了之,记得把error用next()传递回express来做错误处理
• uncaughtException虽然可以让node进程活着,但是已经丢失上下文,你的用户进入了endless world
One more tool
Forever
• 确保脚本在持续运行着• Github: https://github.com/indexzero/
forever
• npm install forever
• forever start app.js