《node.js开发指南》中微博系统
记得我在之前一篇博客《科学家与手艺人》中提到一位大牛,他只比我大一岁,但却已经是一位优秀的工匠了,让我很是佩服,同时也倍感自身的渺小。我说的那位大牛,就是《node.js开发指南》的作者,郭家辉,网名byvoid,清华大学2010级学生,现在在google北京实习(我不是来给他写自传的。。。)。这本书是12年出版的,出来时nodejs还在0.6,express还是2.x,但现在nodejs已经是0.10.5了,express已经是3.x了,书本上很多的代码都已不可用,所以如果照着书上来就会陷入不少的坑中,先来数数都有哪些坑吧:
先贴一份来自github的changelog,express由2.x升级到了3.x,移除的有:
还有一张截自书上的命令行图留做查阅:
中的微博系统
另外,我还了解了一下markdown的语法,找到一篇不错的翻译,感兴趣的朋友看这里
-
res.render()
"status" option (use node's res.statusCode=
or res.status(code).render(...)
)
-
res.render()
"charset" option (use res.charset=
)
-
res.local(foo, bar)
(use res.locals.foo = bar
or res.locals({ foo: bar })
instead)
-
app.dynamicHelpers()
(use middleware + res.locals
)
-
app.helpers()
(use app.locals
)
- the concept of a "layout" (template engine specific now)
-
partial()
(template engine specific)
res.partial()
- "view options" setting, use
app.locals
- "hints" setting
-
req.isXMLHttpRequest
(use req.xhr
)
-
app.error()
(use middleware with (err, req, res, next))
-
req.flash()
(just use sessions: req.session.messages = ['foo']
or similar)
-
connect-flash can be used as middleware to provide req.flash()
- the
jsonp callback
setting was removed (use res.jsonp()
)
发生改变的有:
-
req.header(field[, defaultValue])
replaced by req.get(field)
(remains for backwards compatibility)
-
res.header(field[, value])
replaced by res.set(field, value)
/ res.get(field)
(remains for backwards compatibility)
- renamed
app.register()
to app.engine()
- template engine compliance from
engine.compile(str, options) => Function
to engine.__express(filename, options, callback)
-
express.createServer()
is now simply express()
(but remains for BC).
- Keep in mind that the return value of
express()
is no longer an http.Server
instance. (See the Application function section below for more details)
导致以前很多内置的方法现在必须通过安装插件来支持。好吧,开始数坑:
- express 的-t参数已经失效,必须手动修改app.js和package.json文件来指定文件模块引擎为ejs,默认为jade,需要修改的地方如下:
app.js
app.set('view-engine','ejs');
package.json(*表示最新的版本)"ejs":"*",
- 3.x默认已经不支持flash方法了,必须手动安装
npm install connect-flash
,然后在app.js中加入如下代码:var flash = require('connect-flash'); app.configure(function(){ app.use(flash()); });
- 不支持ejs模块的partials方法,必须手动安装,
npm install express-partials
,然后在app.js中添加如下代码:var partials = require('express-partials'); app.use(partials());
- connect-mongo的用法发生了变化,必须使用下面的写法:
var MongoStore = require('connect-mongo')(express);
注意大小写,settings中用db,则app.js中new MongoStore中也要用db -
partial()path 必须是字符串,例如在index.ejs中,调用say.ejs必须写为
<%- partials('say.ejs') %>
而不能再写为<%- partials('say') %>
,还有就是书上的代码调用post用的是<%- partials('posts') %>
,现在会报错,必须使用<%- partials('posts',{posts:posts})
- 另外,记得要给系统安装Mongodb,不然运行不起来, 教程请看这:Mongodb在Windows下安装及配置 话说mongodb更新的真勤快,最新版本体积暴增,解压后足有200多兆,是原来的三倍左右。
首页截图:
![mb](http://blog.husters.org/wp-content/uploads/2013/05/mb.png)
![nodejsdebug](http://blog.husters.org/wp-content/uploads/2013/05/nodejsdebug.png)