Skip to content
Myr

guide.md

This file

Path

docs/guide.md

713 lines · 20.8 KiB · Markdown

Last changed by

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

History of this file

Take it

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

TasksTj Holowaychukbefore adoption136f677

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

TasksTj Holowaychukbefore adoption136f677

lines 8–11why, one step back
8npm:
910 $ npm install express11

Updated install docsTj Holowaychukbefore adoption193c4a9

line 12why, one step back
12git clone, first update the submodules:

TasksTj Holowaychukbefore adoption136f677

line 13why, one step back
13

Updated install docsTj Holowaychukbefore adoption193c4a9

line 14why, one step back
14 $ git submodule update --init

TasksTj Holowaychukbefore adoption136f677

line 15why, one step back
15 $ make install

Updated install docsTj Holowaychukbefore adoption193c4a9

line 16why, one step back
16 $ make install-support

TasksTj Holowaychukbefore adoption136f677

lines 17–40why, one step back
17
18### 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.

TasksTj Holowaychukbefore adoption136f677

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'));

TasksTj Holowaychukbefore adoption136f677

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 }));

TasksTj Holowaychukbefore adoption136f677

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());

TasksTj Holowaychukbefore adoption136f677

lines 57–81why, 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 });7273To alter the environment we can set the _CONNECT_ENV_ environment variable,74or more specifically _EXPRESS_ENV_, for example:7576 $ EXPRESS_ENV=production node app.js7778### Settings7980Express supports the following settings out of the box:81

Updated docsTj Holowaychukbefore adoption4d32762

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

New "home" docsTj Holowaychukbefore adoption1e7a12f

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

TasksTj Holowaychukbefore adoption136f677

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

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

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

Merge branch 'integration'Tj Holowaychukbefore adoption3fae10d

line 87why, one step back
87 * _partials_ Root view partials directory defaulting to _views_/partials.

TasksTj Holowaychukbefore adoption136f677

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`.

TasksTj Holowaychukbefore adoption136f677

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);

TasksTj Holowaychukbefore adoption136f677

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`.

TasksTj Holowaychukbefore adoption136f677

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"]

TasksTj Holowaychukbefore adoption136f677

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.

TasksTj Holowaychukbefore adoption136f677

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) {

TasksTj Holowaychukbefore adoption136f677

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){

TasksTj Holowaychukbefore adoption136f677

lines 170–177why, one step back
170 // do something else
171 });172173### Middleware174175The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be176passed to _express.createServer()_ as you would with a regular Connect server. For example:177

Updated docsTj Holowaychukbefore adoption344218f

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

TasksTj Holowaychukbefore adoption136f677

lines 179–180why, one step back
179
180 var app = express.createServer(

Updated docsTj Holowaychukbefore adoption344218f

lines 181–182why, one step back
181 express.logger(),
182 express.bodyDecoder()

TasksTj Holowaychukbefore adoption136f677

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

Updated docsTj Holowaychukbefore adoption344218f

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

TasksTj Holowaychukbefore adoption136f677

line 188why, one step back
188

Updated docsTj Holowaychukbefore adoption344218f

lines 189–197why, one step back
189Typically with connect middleware you would _require('connect')_ like so:
190191 var connect = require('connect');192 app.use(connect.logger());193194This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:195196 app.use(express.logger());197

TasksTj Holowaychukbefore adoption136f677

lines 198–223why, one step back
198### Error Handling
199200Express provides the _app.error()_ method which receives exceptions thrown within a route,201or passed to _next(err)_. Below is an example which serves different pages based on our202ad-hoc _NotFound_ exception:203204 function NotFound(msg){205 this.name = 'NotFound';206 Error.call(this, msg);207 Error.captureStackTrace(this, arguments.callee);208 }209210 sys.inherits(NotFound, Error);211212 app.get('/404', function(req, res){213 throw new NotFound;214 });215216 app.get('/500', function(req, res){217 throw new Error('keyboard cat!');218 });219220We can call _app.error()_ several times as shown below.221Here we check for an instanceof _NotFound_ and show the222404 page, or we pass on to the next error handler.223

Merge branch 'fix-error'Tj Holowaychukbefore adoption498115d

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

TasksTj Holowaychukbefore adoption136f677

lines 229–247why, one step back
229 app.error(function(err, req, res, next){
230 if (err instanceof NotFound) {231 res.render('404.jade');232 } else {233 next(err);234 }235 });236237Here we assume all errors as 500 for the simplicity of238this demo, however you can choose whatever you like239240 app.error(function(err, req, res){241 res.render('500.jade', {242 locals: {243 error: err244 } 245 });246 });247

More error handling docsTj Holowaychukbefore adoptioncea401c

lines 248–251why, one step back
248Our apps could also utilize the Connect _errorHandler_ middleware
249to report on exceptions. For example if we wish to output exceptions 250in "development" mode to _stderr_ we can use:251

Updated docsTj Holowaychukbefore adoption344218f

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

More error handling docsTj Holowaychukbefore adoptioncea401c

lines 253–256why, one step back
253
254Also during development we may want fancy html pages to show exceptions255that are passed or thrown, so we can set _showStack_ to true:256

Updated docsTj Holowaychukbefore adoption344218f

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

More error handling docsTj Holowaychukbefore adoptioncea401c

lines 258–261why, one step back
258
259The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_260is present, which is useful for developing apps that rely heavily on client-side JavaScript.261

Added more view docsTj Holowaychukbefore adoption2f96506

lines 262–265why, one step back
262### View Rendering
263264View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name265of the module that will be required. For example the view _layout.ejs_ will

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more view docsTj Holowaychukbefore adoption2f96506

lines 268–278why, one step back
268
269Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,270and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 271the _body_ local variable in _layout.haml_.272273 app.get('/', function(req, res){274 res.render('index.haml', {275 locals: { title: 'My Site' }276 });277 });278

Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b

lines 279–295why, one step back
279The new _view engine_ setting allows us to specify our default template engine,
280so for example when using [Jade](http://github.com/visionmedia/jade) we could set:281282 app.set('view engine', 'jade');283284Allowing us to render with:285286 res.render('index');287288vs:289290 res.render('index.jade');291292When _view engine_ is set, extensions are entirely optional, however we can still293mix and match template engines:294295 res.render('another-page.ejs');

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

lines 296–312why, one step back
296
297Express 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:298299 app.set('view options', {300 layout: false301 });302303Which can then be overridden within the `res.render()` call if need be:304305 res.render('myview.ejs', { layout: true });306307A good example of this is specifying custom _ejs_ opening and closing tags:308309 app.set('view options', {310 open: '{{',311 close: '}}'312 });

Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b

line 313why, one step back
313

Added more view docsTj Holowaychukbefore adoption2f96506

lines 314–331why, one step back
314### View Partials
315316The Express view system has built-in support for partials and collections, which are317sort of "mini" views representing a document fragment. For example rather than iterating318in a view to display comments, we would use a partial with collection support:319320 partial('comment.haml', { collection: comments });321322To make things even less verbose we can assume the extension as _.haml_ when omitted,323however if we wished we could use an ejs partial, within a haml view for example.324325 partial('comment', { collection: comments });326327And once again even further, when rendering a collection we can simply pass328an array, if no other options are desired:329330 partial('comments', comments);331

Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701

lines 332–338why, one step back
332When using the partial collection support a few "magic" variables are provided
333for free:334335 * _firstInCollection_ True if this is the first object336 * _indexInCollection_ Index of the object in the collection337 * _lastInCollection _ True if this is the last object338

Added more view docsTj Holowaychukbefore adoption2f96506

lines 339–346why, one step back
339### Template Engines
340341Below are a few template engines commonly used with Express:342343 * [Jade](http://github.com/visionmedia/jade) haml.js successor344 * [Haml](http://github.com/visionmedia/haml.js) indented templates345 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript346

TasksTj Holowaychukbefore adoption136f677

lines 347–382why, one step back
347### req.header(key[, defaultValue])
348349Get the case-insensitive request header _key_, with optional _defaultValue_:350351 req.header('Host');352 req.header('host');353 req.header('Accept', '*/*');354355### req.accepts(type)356357Check if the _Accept_ header is present, and includes the given _type_.358359When the _Accept_ header is not present _true_ is returned. Otherwise360the given _type_ is matched by an exact match, and then subtypes. You361may pass the subtype such as "html" which is then converted internally362to "text/html" using the mime lookup table.363364 // Accept: text/html365 req.accepts('html');366 // => true367368 // Accept: text/*; application/json369 req.accepts('html');370 req.accepts('text/html');371 req.accepts('text/plain');372 req.accepts('application/json');373 // => true374375 req.accepts('image/png');376 req.accepts('png');377 // => false378379### req.param(name)380381Return the value of param _name_ when present.382

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 383–385why, one step back
383 - Checks route placeholders (_req.params_), ex: /user/:id
384 - Checks query string params (_req.query_), ex: ?id=12385 - Checks urlencoded body params (_req.body_), ex: id=12

TasksTj Holowaychukbefore adoption136f677

lines 386–388why, one step back
386
387To utilize urlencoded request bodies, _req.body_388should be an object. This can be done by using

Updated docsTj Holowaychukbefore adoption344218f

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

TasksTj Holowaychukbefore adoption136f677

lines 390–449why, one step back
390
391### req.flash(type[, msg])392393Queue flash _msg_ of the given _type_.394395 req.flash('info', 'email sent');396 req.flash('error', 'email delivery failed');397 req.flash('info', 'email re-sent');398 // => 2399400 req.flash('info');401 // => ['email sent', 'email re-sent']402403 req.flash('info');404 // => []405406 req.flash();407 // => { error: ['email delivery failed'], info: [] }408409### req.isXMLHttpRequest410411Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header412to see if it was issued by an _XMLHttpRequest_:413414 req.xhr415 req.isXMLHttpRequest416417### res.header(key[, val])418419Get or set the response header _key_.420421 res.header('Content-Length');422 // => undefined423424 res.header('Content-Length', 123);425 // => 123426427 res.header('Content-Length');428 // => 123429430### res.contentType(type)431432Sets the _Content-Type_ response header to the given _type_.433434 var filename = 'path/to/image.png';435 res.contentType(filename);436 // res.headers['Content-Type'] is now "image/png"437438### res.attachment([filename])439440Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.441442 res.attachment('path/to/my/image.png');443444### res.sendfile(path)445446Used by `res.download()` to transfer an arbitrary file. 447448 res.sendfile('path/to/my.file');449

Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1

lines 450–453why, one step back
450This is _not_ a substitution for Connect's _staticProvider_ middleware, it does not
451support HTTP caching, and does not perform any security checks. This method is utilized452by _res.download()_ to transfer static files, and allows you do to so from outside of453the public directory, so suitable security checks should be applied.

TasksTj Holowaychukbefore adoption136f677

lines 454–497why, one step back
454
455### res.download(file[, filename])456457Transfer the given _file_ as an attachment with optional alternative _filename_.458459 res.download('path/to/image.png');460 res.download('path/to/image.png', 'foo.png');461462This is equivalent to:463464 res.attachment(file);465 res.sendfile(file);466467### res.send(body|status[, headers|status[, status]])468469The `res.send()` method is a high level response utility allowing you to pass470objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status471code based responses. The following are all valid uses:472473 res.send(new Buffer('wahoo'));474 res.send({ some: 'json' });475 res.send('<p>some html</p>');476 res.send('Sorry, cant find that', 404);477 res.send('text', { 'Content-Type': 'text/plain' }, 201);478 res.send(404);479480By default the _Content-Type_ response header is set, however if explicitly481assigned through `res.send()` or previously with `res.header()` or `res.contentType()`482it will not be set again.483484### res.redirect(url[, status])485486Redirect to the given _url_ with a default response _status_ of 302.487488 res.redirect('/', 301);489 res.redirect('/account');490 res.redirect('http://google.com');491 res.redirect('home');492 res.redirect('back');493494Express supports "redirect mapping", which by default provides _home_, and _back_.495The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes496the "home" setting and defaults to "/".497

More view docsTj Holowaychukbefore adoption1c8ff48

lines 498–510why, one step back
498### res.render(view[, options[, fn]])
499500Render _view_ with the given _options_ and optional callback _fn_.501When a callback function is given a response will _not_ be made502automatically, however otherwise a response of _200_ and _text/html_ is given.503504 Most engines accept one or more of the following options,505 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:506507 - _context|scope_ Template evaluation context (_this_)508 - _locals_ Object containing local variables509 - _debug_ Output debugging information510

In depth partial docsTj Holowaychukbefore adoption793943f

lines 511–548why, one step back
511### res.partial(view[, options])
512513Render _view_ partial with the given _options_. This method is always available514to the view as a local variable.515516- _as_ Variable name for each _collection_ value, defaults to the view name.517 * as: 'something' will add the _something_ local variable518 * as: this will use the collection value as the template context519 * as: global will merge the collection value's properties with _locals_520521- _collection_ Array of objects, the name is derived from the view name itself. 522 For example _video.html_ will have a object _video_ available to it.523524The following are equivalent, and the name of collection value when passed525to the partial will be _movie_ as derived from the name.526527 partial('movie.jade', { collection: movies });528 partial('movie.jade', movies);529 partial('movie', movies);530 // In view: movie.director531532To change the local from _movie_ to _video_ we can use the "as" option:533534 partial('movie', { collection: movies, as: 'video' });535 // In view: video.director536537Also we can make our movie the value of _this_ within our view so that instead538of _movie.director_ we could use _this.director_.539540 partial('movie', { collection: movies, as: this });541 // In view: this.director542543Another alternative is to "explode" the properties of the collection item into544pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:545546 partials('movie', { collection: movies, as: global });547 // In view: director548

TasksTj Holowaychukbefore adoption136f677

lines 549–553why, one step back
549### app.set(name[, val])
550551Apply an application level setting _name_ to _val_, or552get the value of _name_ when _val_ is not present:553

Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110

lines 554–556why, one step back
554 app.set('views', __dirname + '/views');
555 app.set('views');556 // => ...path...

TasksTj Holowaychukbefore adoption136f677

lines 557–597why, one step back
557
558### app.enable(name)559560Enable the given setting _name_:561562 app.enable('some arbitrary setting');563 app.set('some arbitrary setting');564 // => true565566### app.disable(name)567568Disable the given setting _name_:569570 app.disable('some setting');571 app.set('some setting');572 // => false573574### app.configure(env|function[, function])575576Define a callback function for the given _env_ (or all environments) with callback _function_:577578 app.configure(function(){579 // executed for each env580 });581582 app.configure('development', function(){583 // executed for 'development' only584 });585586### app.redirect(name, val)587588For use with `res.redirect()` we can map redirects at the application level as shown below:589590 app.redirect('google', 'http://google.com');591592Now in a route we may call:593594 res.redirect('google');595596We may also map dynamic redirects:597

Updated docsTj Holowaychukbefore adoptiond691ecb

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

TasksTj Holowaychukbefore adoption136f677

lines 600–618why, one step back
600 });
601602So now we may do the following, and the redirect will dynamically adjust to603the context of the request. If we called this route with _GET /post/12_ our604redirect _Location_ would be _/post/12/comments_.605606 app.get('/post/:id', function(req, res){607 res.redirect('comments');608 });609610### app.error(function)611612Adds an error handler _function_ which will receive the exception as the first parameter as shown below.613Note that we may set several error handlers by making several calls to this method, however the handler614should call _next(err)_ if it does not wish to deal with the exception:615616 app.error(function(err, req, res, next){617 res.send(err.message, 500);618 });

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 619–621why, one step back
619
620### app.helpers(obj)621

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

lines 622–637why, one step back
622Registers static view helpers.
623624 app.helpers({625 name: function(first, last){ return first + ', ' + last },626 firstName: 'tj',627 lastName: 'holowaychuk'628 });629630Our view could now utilize the _firstName_ and _lastName_ variables,631as well as the _name()_ function exposed.632633 <%= name(firstName, lastName) %>634635### app.dynamicHelpers(obj)636637Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

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

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 644–647why, one step back
644 return req.session;
645 }646 });647

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

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 651–664why, one step back
651
652### app.mounted(fn)653654Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.655656 var app = express.createServer(),657 blog = express.createServer();658 659 blog.mounted(function(parent){660 // parent is app661 // "this" is blog662 });663 664 app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 665–689why, one step back
665
666### app.register(ext, exports)667668Register the given template engine _exports_669as _ext_. For example we may wish to map ".html"670files to jade:671672 app.register('.html', require('jade'));673674This is also useful for libraries that may not675match extensions correctly. For example my haml.js676library is installed from npm as "hamljs" so instead677of layout.hamljs, we can register the engine as ".haml":678679 app.register('.haml', require('haml-js'));680681For engines that do not comply with the Express682specification, we can also wrap their api this way.683684 app.register('.foo', {685 render: function(str, options) {686 // perhaps their api is687 // foo.toHTML(str, options);688 }689 });

TasksTj Holowaychukbefore adoption136f677

lines 690–713why, one step back
690
691### app.listen([port[, host]])692693Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all694connections will be accepted via _INADDR_ANY_.695696 app.listen();697 app.listen(3000);698 app.listen(3000, 'n.n.n.n');699700The _port_ argument may also be a string representing the path to a unix domain socket:701702 app.listen('/tmp/express.sock');703704Then try it out:705706 $ telnet /tmp/express.sock707 GET / HTTP/1.1708709 HTTP/1.1 200 OK710 Content-Type: text/plain711 Content-Length: 11712 713 Hello World