Skip to content
Myr

guide.md

This file

Path

docs/guide.md

802 lines · 24.7 KiB · Markdown

Last changed by

Merge branch 'master' into rangeTj Holowaychukbefore adoptionc3365aa

History of this file

Take it

The walk stopped after 200 commits: lines older than b40a241 point at it.

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 1–3why, one step back
1
2### Installation3

No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9

line 4why, one step back
4curl:

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

lines 5–7why, one step back
5
6 $ curl -# http://expressjs.com/install.sh | sh7

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 8–40why, one step back
8npm:
910 $ npm install express1112git clone, first update the submodules:1314 $ git submodule update --init15 $ make install16 $ make install-support1718### Creating An Application1920The _express.Server_ now inherits from _http.Server_, however21follows the same idiom by providing _express.createServer()_ as shown below. This means22that you can utilize Express server's transparently with other libraries.2324 var app = require('express').createServer();25 26 app.get('/', function(req, res){27 res.send('hello world');28 });29 30 app.listen(3000);3132### Configuration3334Express supports arbitrary environments, such as _production_ and _development_. Developers35can use the _configure()_ method to setup needs required by the current environment. When36_configure()_ is called without an environment name it will be run in _every_ environment 37prior to the environment specific callback.3839In the example below we only _dumpExceptions_, and respond with exception stack traces40in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

lines 41–42why, one step back
41Note the use of _app.router_, which can (optionally) be used to mount the application routes,
42otherwise the first call to _app.{get,put,del,post}()_ will mount the routes.

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 43–44why, one step back
43
44 app.configure(function(){

Updated docsTj Holowaychukbefore adoption344218f

lines 45–46why, one step back
45 app.use(express.methodOverride());
46 app.use(express.bodyDecoder());

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

line 47why, one step back
47 app.use(app.router);

Updated docsTj Holowaychukbefore adoption344218f

line 48why, one step back
48 app.use(express.staticProvider(__dirname + '/public'));

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 49–51why, one step back
49 });
50 51 app.configure('development', function(){

Updated docsTj Holowaychukbefore adoption344218f

line 52why, one step back
52 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 53–55why, one step back
53 });
54 55 app.configure('production', function(){

Updated docsTj Holowaychukbefore adoption344218f

line 56why, one step back
56 app.use(express.errorHandler());

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 57–72why, one step back
57 });
5859For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:6061 app.configure(function(){62 app.set('views', __dirname + '/views');63 app.set('views');64 // => "... views directory ..."65 66 app.enable('some feature');67 // same as app.set('some feature', true);68 69 app.disable('some feature');70 // same as app.set('some feature', false);71 });72

Merge branch 'master' into rangeTj Holowaychukbefore adoptionc3365aa

line 73why, one step back
73To alter the environment we can set the _NODE_ENV_ environment variable, for example:

Better blog partialsTj Holowaychukbefore adoptionb40a241

line 74why, one step back
74

Merge branch 'master' into rangeTj Holowaychukbefore adoptionc3365aa

line 75why, one step back
75 $ NODE_ENV=production node app.js

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 76–80why, one step back
76
77### Settings7879Express supports the following settings out of the box:80

Updated docsTj Holowaychukbefore adoption4d32762

line 81why, one step back
81 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_

New "home" docsTj Holowaychukbefore adoption1e7a12f

line 82why, one step back
82 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 83–84why, one step back
83 * _views_ Root views directory defaulting to **CWD/views**
84 * _view engine_ Default view engine name for views rendered without extensions

Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c

line 85why, one step back
85 * _view options_ An object specifying global view options

Merge branch 'downloads'Tj Holowaychukbefore adoption949803d

lines 86–87why, one step back
86 * _partials_ Root view partials directory defaulting to _views_/partials.
87 * _stream threshold_ Bytesize indicating when a file should be streamed for _res.sendfile()_ using _fs.ReadStream()_ and _sys.pump()_.

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 88–92why, one step back
88
89### Routing9091Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.92For example we may want to render a user's account for the path _/user/12_, this

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 93–94why, one step back
93can be done by defining the route below. The values associated to the named placeholders
94are available as `req.params`.

Better blog partialsTj Holowaychukbefore adoptionb40a241

line 95why, one step back
95

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 96–97why, one step back
96 app.get('/user/:id', function(req, res){
97 res.send('user ' + req.params.id);

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 98–104why, one step back
98 });
99100A route is simple a string which is compiled to a _RegExp_ internally. For example101when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:102103 \/user\/([^\/]+)\/?104

Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b

line 105why, one step back
105Regular expression literals may also be passed for complex uses. Since capture

Updated docsTj Holowaychukbefore adoptiond691ecb

line 106why, one step back
106groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.

Better blog partialsTj Holowaychukbefore adoptionb40a241

line 107why, one step back
107

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 108–109why, one step back
108 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){
109 res.send(req.params);

Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b

lines 110–121why, one step back
110 });
111112Curl requests against the previously defined route:113114 $ curl http://dev:3000/user115 [null,null]116 $ curl http://dev:3000/users117 [null,null]118 $ curl http://dev:3000/users/1119 ["1",null]120 $ curl http://dev:3000/users/1..15121 ["1","15"]

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 122–155why, one step back
122
123Below are some route examples, and the associated paths that they124may consume:125126 "/user/:id"127 /user/12128129 "/users/:id?"130 /users/5131 /users132133 "/files/*"134 /files/jquery.js135 /files/javascripts/jquery.js136137 "/file/*.*"138 /files/jquery.js139 /files/javascripts/jquery.js140 141 "/user/:id/:operation?"142 /user/1143 /user/1/edit144 145 "/products.:format"146 /products.json147 /products.xml148149 "/products.:format?"150 /products.json151 /products.xml152 /products153154### Passing Route Control155

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 156–158why, one step back
156We may pass control to the next _matching_ route, by calling the _third_ argument,
157the _next()_ function. When a match cannot be made, control is passed back to Connect,158and middleware continue to be invoked.

Better blog partialsTj Holowaychukbefore adoptionb40a241

line 159why, one step back
159

Fixed doc typoTj Holowaychukbefore adoption47ff7d9

line 160why, one step back
160 app.get('/users/:id?', function(req, res, next){

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 161–162why, one step back
161 var id = req.params.id;
162 if (id) {

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 163–168why, one step back
163 // do something
164 } else {165 next();166 }167 });168

Updated docsTj Holowaychukbefore adoptiond691ecb

line 169why, one step back
169 app.get('/users', function(req, res){

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 170–172why, one step back
170 // do something else
171 });172

Merge branch 'master' into rangeTj Holowaychukbefore adoptionc3365aa

lines 173–214why, one step back
173### HTTP Methods
174175We have seen _app.get()_ a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as _app.post()_, _app.del()_, etc.176177 A common example for _POST_ usage, is when "submitting" a form. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it.178 179 <form method="post" action="/">180 <input type="text" name="user[name]" />181 <input type="text" name="user[email]" />182 <input type="submit" value="Submit" />183 </form>184185By default Express does not know what to do with this request body, so we should add the _bodyDecoder_ middleware, which will parse _application/x-www-form-urlencoded_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:186187 app.use(express.bodyDecoder());188189Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.190191 app.post('/', function(req, res){192 console.log(req.body.user);193 res.redirect('back');194 });195196When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyDecoder_ so that it can utilize it's _req.body_ containing the form values.197198 app.use(express.bodyDecoder());199 app.use(express.methodOverride());200201The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as _PUT_ and _DELETE_ can still be accessed by clients which can use them directly, although _methodOverride_ provides a great solution for forms. Below shows what the usage of _PUT_ might look like:202203 <form method="post" action="/">204 <input type="hidden" name="_method" value="put" />205 <input type="text" name="user[name]" />206 <input type="text" name="user[email]" />207 <input type="submit" value="Submit" /> 208 </form>209210 app.put('/', function(){211 console.log(req.body.user);212 res.redirect('back');213 });214

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 215–216why, one step back
215### Middleware
216

Fixed Connect linksTj Holowaychukbefore adoptiona2e93eb

line 217why, one step back
217The Express _Plugin_ is no more! middleware via [Connect](http://github.com/senchalabs/connect) can be

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 218–219why, one step back
218passed to _express.createServer()_ as you would with a regular Connect server. For example:
219

Updated docsTj Holowaychukbefore adoption344218f

line 220why, one step back
220 var express = require('express');

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 221–222why, one step back
221
222 var app = express.createServer(

Updated docsTj Holowaychukbefore adoption344218f

lines 223–224why, one step back
223 express.logger(),
224 express.bodyDecoder()

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 225–228why, one step back
225 );
226227Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:228

Updated docsTj Holowaychukbefore adoption344218f

line 229why, one step back
229 app.use(express.logger({ format: ':method :uri' }));

Better blog partialsTj Holowaychukbefore adoptionb40a241

line 230why, one step back
230

Updated docsTj Holowaychukbefore adoption344218f

lines 231–239why, one step back
231Typically with connect middleware you would _require('connect')_ like so:
232233 var connect = require('connect');234 app.use(connect.logger());235236This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:237238 app.use(express.logger());239

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 240–265why, one step back
240### Error Handling
241242Express provides the _app.error()_ method which receives exceptions thrown within a route,243or passed to _next(err)_. Below is an example which serves different pages based on our244ad-hoc _NotFound_ exception:245246 function NotFound(msg){247 this.name = 'NotFound';248 Error.call(this, msg);249 Error.captureStackTrace(this, arguments.callee);250 }251252 sys.inherits(NotFound, Error);253254 app.get('/404', function(req, res){255 throw new NotFound;256 });257258 app.get('/500', function(req, res){259 throw new Error('keyboard cat!');260 });261262We can call _app.error()_ several times as shown below.263Here we check for an instanceof _NotFound_ and show the264404 page, or we pass on to the next error handler.265

Merge branch 'fix-error'Tj Holowaychukbefore adoption498115d

lines 266–270why, one step back
266Note that these handlers can be defined anywhere, as they
267will be placed below the route handlers on _listen()_. This 268allows for definition within _configure()_ blocks so we can269handle exceptions in different ways based on the environment.270

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 271–293why, one step back
271 app.error(function(err, req, res, next){
272 if (err instanceof NotFound) {273 res.render('404.jade');274 } else {275 next(err);276 }277 });278279Here we assume all errors as 500 for the simplicity of280this demo, however you can choose whatever you like281282 app.error(function(err, req, res){283 res.render('500.jade', {284 locals: {285 error: err286 } 287 });288 });289290Our apps could also utilize the Connect _errorHandler_ middleware291to report on exceptions. For example if we wish to output exceptions 292in "development" mode to _stderr_ we can use:293

Updated docsTj Holowaychukbefore adoption344218f

line 294why, one step back
294 app.use(express.errorHandler({ dumpExceptions: true }));

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 295–298why, one step back
295
296Also during development we may want fancy html pages to show exceptions297that are passed or thrown, so we can set _showStack_ to true:298

Updated docsTj Holowaychukbefore adoption344218f

line 299why, one step back
299 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 300–307why, one step back
300
301The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_302is present, which is useful for developing apps that rely heavily on client-side JavaScript.303304### View Rendering305306View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name307of the module that will be required. For example the view _layout.ejs_ will

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 308–309why, one step back
308tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however
309_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 310–337why, one step back
310
311Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,312and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 313the _body_ local variable in _layout.haml_.314315 app.get('/', function(req, res){316 res.render('index.haml', {317 locals: { title: 'My Site' }318 });319 });320321The new _view engine_ setting allows us to specify our default template engine,322so for example when using [Jade](http://github.com/visionmedia/jade) we could set:323324 app.set('view engine', 'jade');325326Allowing us to render with:327328 res.render('index');329330vs:331332 res.render('index.jade');333334When _view engine_ is set, extensions are entirely optional, however we can still335mix and match template engines:336337 res.render('another-page.ejs');

Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c

lines 338–347why, one step back
338
339Express also provides the _view options_ setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:340341 app.set('view options', {342 layout: false343 });344345Which can then be overridden within the `res.render()` call if need be:346347 res.render('myview.ejs', { layout: true });

Merge branch 'master' into rangeTj Holowaychukbefore adoptionc3365aa

lines 348–359why, one step back
348
349When an alternate layout is required, we may also specify a path. For example if we have _view engine_ set to _jade_ and a file named _./views/mylayout.jade_ we can simply pass:350351 res.render('page', { layout: 'mylayout' });352353Otherwise we must specify the extension:354355 res.render('page', { layout: 'mylayout.jade' });356357These paths may also be absolute:358359 res.render('page', { layout: __dirname + '/../../mylayout.jade' });

Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c

lines 360–366why, one step back
360
361A good example of this is specifying custom _ejs_ opening and closing tags:362363 app.set('view options', {364 open: '{{',365 close: '}}'366 });

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 367–390why, one step back
367
368### View Partials369370The Express view system has built-in support for partials and collections, which are371sort of "mini" views representing a document fragment. For example rather than iterating372in a view to display comments, we would use a partial with collection support:373374 partial('comment.haml', { collection: comments });375376To make things even less verbose we can assume the extension as _.haml_ when omitted,377however if we wished we could use an ejs partial, within a haml view for example.378379 partial('comment', { collection: comments });380381And once again even further, when rendering a collection we can simply pass382an array, if no other options are desired:383384 partial('comments', comments);385386When using the partial collection support a few "magic" variables are provided387for free:388389 * _firstInCollection_ True if this is the first object390 * _indexInCollection_ Index of the object in the collection

Doc typosTj Holowaychukbefore adoption02b4ec0

line 391why, one step back
391 * _lastInCollection_ True if this is the last object

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 392–396why, one step back
392
393### Template Engines394395Below are a few template engines commonly used with Express:396

Doc typosTj Holowaychukbefore adoption02b4ec0

lines 397–398why, one step back
397 * [Jade](http://jade-lang.com) haml.js successor
398 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templates

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 399–436why, one step back
399 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript
400401### req.header(key[, defaultValue])402403Get the case-insensitive request header _key_, with optional _defaultValue_:404405 req.header('Host');406 req.header('host');407 req.header('Accept', '*/*');408409### req.accepts(type)410411Check if the _Accept_ header is present, and includes the given _type_.412413When the _Accept_ header is not present _true_ is returned. Otherwise414the given _type_ is matched by an exact match, and then subtypes. You415may pass the subtype such as "html" which is then converted internally416to "text/html" using the mime lookup table.417418 // Accept: text/html419 req.accepts('html');420 // => true421422 // Accept: text/*; application/json423 req.accepts('html');424 req.accepts('text/html');425 req.accepts('text/plain');426 req.accepts('application/json');427 // => true428429 req.accepts('image/png');430 req.accepts('png');431 // => false432433### req.param(name)434435Return the value of param _name_ when present.436

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 437–439why, one step back
437 - Checks route placeholders (_req.params_), ex: /user/:id
438 - Checks query string params (_req.query_), ex: ?id=12439 - Checks urlencoded body params (_req.body_), ex: id=12

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 440–442why, one step back
440
441To utilize urlencoded request bodies, _req.body_442should be an object. This can be done by using

Updated docsTj Holowaychukbefore adoption344218f

line 443why, one step back
443the _express.bodyDecoder_ middleware.

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 444–462why, one step back
444
445### req.flash(type[, msg])446447Queue flash _msg_ of the given _type_.448449 req.flash('info', 'email sent');450 req.flash('error', 'email delivery failed');451 req.flash('info', 'email re-sent');452 // => 2453454 req.flash('info');455 // => ['email sent', 'email re-sent']456457 req.flash('info');458 // => []459460 req.flash();461 // => { error: ['email delivery failed'], info: [] }462

Added flash formatter docsTj Holowaychukbefore adoptionf16978d

lines 463–466why, one step back
463Flash notification message may also utilize formatters, by default only the %s string formatter is available:
464465 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);466

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 467–507why, one step back
467### req.isXMLHttpRequest
468469Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header470to see if it was issued by an _XMLHttpRequest_:471472 req.xhr473 req.isXMLHttpRequest474475### res.header(key[, val])476477Get or set the response header _key_.478479 res.header('Content-Length');480 // => undefined481482 res.header('Content-Length', 123);483 // => 123484485 res.header('Content-Length');486 // => 123487488### res.contentType(type)489490Sets the _Content-Type_ response header to the given _type_.491492 var filename = 'path/to/image.png';493 res.contentType(filename);494 // res.headers['Content-Type'] is now "image/png"495496### res.attachment([filename])497498Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.499500 res.attachment('path/to/my/image.png');501502### res.sendfile(path)503504Used by `res.download()` to transfer an arbitrary file. 505506 res.sendfile('path/to/my.file');507

Merge branch 'downloads'Tj Holowaychukbefore adoption949803d

lines 508–518why, one step back
508This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has __not__ been streamed, _next(err)_ will be called on an exception.
509510 res.sendfile(path, function(err, path){511 if (err) {512 // handle the error513 } else {514 console.log('transferred %s', path);515 }516 });517518When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 519–537why, one step back
519
520### res.download(file[, filename])521522Transfer the given _file_ as an attachment with optional alternative _filename_.523524 res.download('path/to/image.png');525 res.download('path/to/image.png', 'foo.png');526527This is equivalent to:528529 res.attachment(file);530 res.sendfile(file);531532### res.send(body|status[, headers|status[, status]])533534The `res.send()` method is a high level response utility allowing you to pass535objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status536code based responses. The following are all valid uses:537

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d

line 538why, one step back
538 res.send(); // 204

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 539–563why, one step back
539 res.send(new Buffer('wahoo'));
540 res.send({ some: 'json' });541 res.send('<p>some html</p>');542 res.send('Sorry, cant find that', 404);543 res.send('text', { 'Content-Type': 'text/plain' }, 201);544 res.send(404);545546By default the _Content-Type_ response header is set, however if explicitly547assigned through `res.send()` or previously with `res.header()` or `res.contentType()`548it will not be set again.549550### res.redirect(url[, status])551552Redirect to the given _url_ with a default response _status_ of 302.553554 res.redirect('/', 301);555 res.redirect('/account');556 res.redirect('http://google.com');557 res.redirect('home');558 res.redirect('back');559560Express supports "redirect mapping", which by default provides _home_, and _back_.561The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes562the "home" setting and defaults to "/".563

Cookie docsTj Holowaychukbefore adoptiona89767c

lines 564–584why, one step back
564### res.cookie(name, val[, options])
565566Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.567568 // "Remember me" for 15 minutes 569 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });570571To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:572573 app.use(express.cookieDecoder());574 575 app.get('/', function(req, res){576 // use req.cookies.rememberme577 });578579### res.clearCookie(name)580581Clear cookie _name_ by setting "expires" far in the past.582583 res.clearCookie('rememberme');584

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 585–593why, one step back
585### res.render(view[, options[, fn]])
586587Render _view_ with the given _options_ and optional callback _fn_.588When a callback function is given a response will _not_ be made589automatically, however otherwise a response of _200_ and _text/html_ is given.590591 Most engines accept one or more of the following options,592 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:593

Updated docsTj Holowaychukbefore adoptionfd4c88d

line 594why, one step back
594 - _scope_ Template evaluation context (value of _this_)

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 595–596why, one step back
595 - _locals_ Object containing local variables
596 - _debug_ Output debugging information

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d

lines 597–598why, one step back
597 - _status_ Response status code, defaults to 200
598 - _headers_ Response headers object

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 599–642why, one step back
599
600### res.partial(view[, options])601602Render _view_ partial with the given _options_. This method is always available603to the view as a local variable.604605- _as_ Variable name for each _collection_ value, defaults to the view name.606 * as: 'something' will add the _something_ local variable607 * as: this will use the collection value as the template context608 * as: global will merge the collection value's properties with _locals_609610- _collection_ Array of objects, the name is derived from the view name itself. 611 For example _video.html_ will have a object _video_ available to it.612613The following are equivalent, and the name of collection value when passed614to the partial will be _movie_ as derived from the name.615616 partial('movie.jade', { collection: movies });617 partial('movie.jade', movies);618 partial('movie', movies);619 // In view: movie.director620621To change the local from _movie_ to _video_ we can use the "as" option:622623 partial('movie', { collection: movies, as: 'video' });624 // In view: video.director625626Also we can make our movie the value of _this_ within our view so that instead627of _movie.director_ we could use _this.director_.628629 partial('movie', { collection: movies, as: this });630 // In view: this.director631632Another alternative is to "explode" the properties of the collection item into633pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:634635 partials('movie', { collection: movies, as: global });636 // In view: director637638### app.set(name[, val])639640Apply an application level setting _name_ to _val_, or641get the value of _name_ when _val_ is not present:642

Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110

lines 643–645why, one step back
643 app.set('views', __dirname + '/views');
644 app.set('views');645 // => ...path...

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 646–686why, one step back
646
647### app.enable(name)648649Enable the given setting _name_:650651 app.enable('some arbitrary setting');652 app.set('some arbitrary setting');653 // => true654655### app.disable(name)656657Disable the given setting _name_:658659 app.disable('some setting');660 app.set('some setting');661 // => false662663### app.configure(env|function[, function])664665Define a callback function for the given _env_ (or all environments) with callback _function_:666667 app.configure(function(){668 // executed for each env669 });670671 app.configure('development', function(){672 // executed for 'development' only673 });674675### app.redirect(name, val)676677For use with `res.redirect()` we can map redirects at the application level as shown below:678679 app.redirect('google', 'http://google.com');680681Now in a route we may call:682683 res.redirect('google');684685We may also map dynamic redirects:686

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 687–688why, one step back
687 app.redirect('comments', function(req, res){
688 return '/post/' + req.params.id + '/comments';

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 689–707why, one step back
689 });
690691So now we may do the following, and the redirect will dynamically adjust to692the context of the request. If we called this route with _GET /post/12_ our693redirect _Location_ would be _/post/12/comments_.694695 app.get('/post/:id', function(req, res){696 res.redirect('comments');697 });698699### app.error(function)700701Adds an error handler _function_ which will receive the exception as the first parameter as shown below.702Note that we may set several error handlers by making several calls to this method, however the handler703should call _next(err)_ if it does not wish to deal with the exception:704705 app.error(function(err, req, res, next){706 res.send(err.message, 500);707 });

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 708–710why, one step back
708
709### app.helpers(obj)710

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

lines 711–726why, one step back
711Registers static view helpers.
712713 app.helpers({714 name: function(first, last){ return first + ', ' + last },715 firstName: 'tj',716 lastName: 'holowaychuk'717 });718719Our view could now utilize the _firstName_ and _lastName_ variables,720as well as the _name()_ function exposed.721722 <%= name(firstName, lastName) %>723724### app.dynamicHelpers(obj)725726Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

line 727why, one step back
727are simply functions which accept _req_, _res_, and are

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

line 728why, one step back
728evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 729–730why, one step back
729becomes the local variable it is associated with.
730

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

line 731why, one step back
731 app.dynamicHelpers({

Updated docsTj Holowaychukbefore adoptiond691ecb

line 732why, one step back
732 session: function(req, res){

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 733–736why, one step back
733 return req.session;
734 }735 });736

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

lines 737–739why, one step back
737All views would now have _session_ available so that session data can be accessed via _session.name_ etc:
738739 <%= session.name %>

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 740–753why, one step back
740
741### app.mounted(fn)742743Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.744745 var app = express.createServer(),746 blog = express.createServer();747 748 blog.mounted(function(parent){749 // parent is app750 // "this" is blog751 });752 753 app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 754–778why, one step back
754
755### app.register(ext, exports)756757Register the given template engine _exports_758as _ext_. For example we may wish to map ".html"759files to jade:760761 app.register('.html', require('jade'));762763This is also useful for libraries that may not764match extensions correctly. For example my haml.js765library is installed from npm as "hamljs" so instead766of layout.hamljs, we can register the engine as ".haml":767768 app.register('.haml', require('haml-js'));769770For engines that do not comply with the Express771specification, we can also wrap their api this way.772773 app.register('.foo', {774 render: function(str, options) {775 // perhaps their api is776 // foo.toHTML(str, options);777 }778 });

Better blog partialsTj Holowaychukbefore adoptionb40a241

lines 779–802why, one step back
779
780### app.listen([port[, host]])781782Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all783connections will be accepted via _INADDR_ANY_.784785 app.listen();786 app.listen(3000);787 app.listen(3000, 'n.n.n.n');788789The _port_ argument may also be a string representing the path to a unix domain socket:790791 app.listen('/tmp/express.sock');792793Then try it out:794795 $ telnet /tmp/express.sock796 GET / HTTP/1.1797798 HTTP/1.1 200 OK799 Content-Type: text/plain800 Content-Length: 11801 802 Hello World