Skip to content
Myr

guide.md

This file

Path

docs/guide.md

658 lines · 19.0 KiB · Markdown

Last changed by

Added "partials" setting to docsTj Holowaychukbefore adoptiond775154

History of this file

Take it

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

TasksTj Holowaychukbefore adoptiondf7582b

line 1why, one step back
1

Install docsTj Holowaychukbefore adoption63d02f1

lines 2–3why, one step back
2### Installation
3

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

Install docsTj Holowaychukbefore adoption63d02f1

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:

Install docsTj Holowaychukbefore adoption63d02f1

line 13why, one step back
13

Updated install docsTj Holowaychukbefore adoption193c4a9

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

Install docsTj Holowaychukbefore adoption63d02f1

line 15why, one step back
15 $ make install

Updated install docsTj Holowaychukbefore adoption193c4a9

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

Install docsTj Holowaychukbefore adoption63d02f1

line 17why, one step back
17

TasksTj Holowaychukbefore adoptiondf7582b

lines 18–40why, one step back
18### Creating An Application
1920The _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 adoptiondf7582b

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

lines 47–48why, one step back
47 app.use(app.router);
48 app.use(connect.staticProvider(__dirname + '/public'));

TasksTj Holowaychukbefore adoptiondf7582b

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

TasksTj Holowaychukbefore adoptiondf7582b

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

TasksTj Holowaychukbefore adoptiondf7582b

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

More docsTj Holowaychukbefore adoptionde81ee7

lines 73–77why, one step back
73To alter the environment we can set the _CONNECT_ENV_ environment variable,
74or more specifically _EXPRESS_ENV_, for example:7576 $ EXPRESS_ENV=production node app.js77

TasksTj Holowaychukbefore adoptiondf7582b

lines 78–81why, one step back
78### Settings
7980Express 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 adoptiondf7582b

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

Added "partials" setting to docsTj Holowaychukbefore adoptiond775154

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

TasksTj Holowaychukbefore adoptiondf7582b

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

TasksTj Holowaychukbefore adoptiondf7582b

line 94why, one step back
94

Updated docsTj Holowaychukbefore adoptiond691ecb

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

TasksTj Holowaychukbefore adoptiondf7582b

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

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

TasksTj Holowaychukbefore adoptiondf7582b

line 106why, one step back
106

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

lines 109–120why, one step back
109 });
110111Curl requests against the previously defined route:112113 $ curl http://dev:3000/user114 [null,null]115 $ curl http://dev:3000/users116 [null,null]117 $ curl http://dev:3000/users/1118 ["1",null]119 $ curl http://dev:3000/users/1..15120 ["1","15"]

TasksTj Holowaychukbefore adoptiondf7582b

lines 121–154why, one step back
121
122Below are some route examples, and the associated paths that they123may consume:124125 "/user/:id"126 /user/12127128 "/users/:id?"129 /users/5130 /users131132 "/files/*"133 /files/jquery.js134 /files/javascripts/jquery.js135136 "/file/*.*"137 /files/jquery.js138 /files/javascripts/jquery.js139 140 "/user/:id/:operation?"141 /user/1142 /user/1/edit143 144 "/products.:format"145 /products.json146 /products.xml147148 "/products.:format?"149 /products.json150 /products.xml151 /products152153### Passing Route Control154

Updated docsTj Holowaychukbefore adoptiond691ecb

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

TasksTj Holowaychukbefore adoptiondf7582b

line 158why, one step back
158

Fixed doc typoTj Holowaychukbefore adoption47ff7d9

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

TasksTj Holowaychukbefore adoptiondf7582b

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

TasksTj Holowaychukbefore adoptiondf7582b

lines 169–184why, one step back
169 // do something else
170 });171172### Middleware173174The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be175passed to _express.createServer()_ as you would with a regular Connect server. For example:176177 var connect = require('connect'),178 express = require('express');179180 var app = express.createServer(181 connect.logger(),182 connect.bodyDecoder()183 );184

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 188–233why, one step back
188
189### Error Handling190191Express provides the _app.error()_ method which receives exceptions thrown within a route,192or passed to _next(err)_. Below is an example which serves different pages based on our193ad-hoc _NotFound_ exception:194195 function NotFound(msg){196 this.name = 'NotFound';197 Error.call(this, msg);198 Error.captureStackTrace(this, arguments.callee);199 }200201 sys.inherits(NotFound, Error);202203 app.get('/404', function(req, res){204 throw new NotFound;205 });206207 app.get('/500', function(req, res){208 throw new Error('keyboard cat!');209 });210211We can call _app.error()_ several times as shown below.212Here we check for an instanceof _NotFound_ and show the213404 page, or we pass on to the next error handler.214215 app.error(function(err, req, res, next){216 if (err instanceof NotFound) {217 res.render('404.jade');218 } else {219 next(err);220 }221 });222223Here we assume all errors as 500 for the simplicity of224this demo, however you can choose whatever you like225226 app.error(function(err, req, res){227 res.render('500.jade', {228 locals: {229 error: err230 } 231 });232 });233

More error handling docsTj Holowaychukbefore adoptioncea401c

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

More error handling docsTj Holowaychukbefore adoptioncea401c

lines 239–242why, one step back
239
240Also during development we may want fancy html pages to show exceptions241that are passed or thrown, so we can set _showStack_ to true:242

Updated docsTj Holowaychukbefore adoptioncacada8

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

More error handling docsTj Holowaychukbefore adoptioncea401c

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

Added more view docsTj Holowaychukbefore adoption2f96506

lines 248–265why, one step back
248### View Rendering
249250View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name251of the module that will be required. For example the view _layout.ejs_ will252tell the view system to _require('ejs')_, the module being loaded must (currently)253export the method _exports.render(str, options)_ to comply with Express, however 254with will likely be extensible in the future.255256Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,257and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 258the _body_ local variable in _layout.haml_.259260 app.get('/', function(req, res){261 res.render('index.haml', {262 locals: { title: 'My Site' }263 });264 });265

Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b

lines 266–283why, one step back
266The new _view engine_ setting allows us to specify our default template engine,
267so for example when using [Jade](http://github.com/visionmedia/jade) we could set:268269 app.set('view engine', 'jade');270271Allowing us to render with:272273 res.render('index');274275vs:276277 res.render('index.jade');278279When _view engine_ is set, extensions are entirely optional, however we can still280mix and match template engines:281282 res.render('another-page.ejs');283

Added more view docsTj Holowaychukbefore adoption2f96506

lines 284–301why, one step back
284### View Partials
285286The Express view system has built-in support for partials and collections, which are287sort of "mini" views representing a document fragment. For example rather than iterating288in a view to display comments, we would use a partial with collection support:289290 partial('comment.haml', { collection: comments });291292To make things even less verbose we can assume the extension as _.haml_ when omitted,293however if we wished we could use an ejs partial, within a haml view for example.294295 partial('comment', { collection: comments });296297And once again even further, when rendering a collection we can simply pass298an array, if no other options are desired:299300 partial('comments', comments);301

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

lines 302–308why, one step back
302When using the partial collection support a few "magic" variables are provided
303for free:304305 * _firstInCollection_ True if this is the first object306 * _indexInCollection_ Index of the object in the collection307 * _lastInCollection _ True if this is the last object308

Added more view docsTj Holowaychukbefore adoption2f96506

lines 309–316why, one step back
309### Template Engines
310311Below are a few template engines commonly used with Express:312313 * [Jade](http://github.com/visionmedia/jade) haml.js successor314 * [Haml](http://github.com/visionmedia/haml.js) indented templates315 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript316

More docsTj Holowaychukbefore adoptionde81ee7

line 317why, one step back
317### req.header(key[, defaultValue])

More docsTj Holowaychukbefore adoptiondfecbe5

lines 318–324why, one step back
318
319Get the case-insensitive request header _key_, with optional _defaultValue_:320321 req.header('Host');322 req.header('host');323 req.header('Accept', '*/*');324

More docsTj Holowaychukbefore adoptionde81ee7

line 325why, one step back
325### req.accepts(type)

More docsTj Holowaychukbefore adoptiondfecbe5

lines 326–348why, one step back
326
327Check if the _Accept_ header is present, and includes the given _type_.328329When the _Accept_ header is not present _true_ is returned. Otherwise330the given _type_ is matched by an exact match, and then subtypes. You331may pass the subtype such as "html" which is then converted internally332to "text/html" using the mime lookup table.333334 // Accept: text/html335 req.accepts('html');336 // => true337338 // Accept: text/*; application/json339 req.accepts('html');340 req.accepts('text/html');341 req.accepts('text/plain');342 req.accepts('application/json');343 // => true344345 req.accepts('image/png');346 req.accepts('png');347 // => false348

More docsTj Holowaychukbefore adoptionde81ee7

line 349why, one step back
349### req.param(name)

More docsTj Holowaychukbefore adoptiondfecbe5

lines 350–352why, one step back
350
351Return the value of param _name_ when present.352

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 353–355why, one step back
353 - Checks route placeholders (_req.params_), ex: /user/:id
354 - Checks query string params (_req.query_), ex: ?id=12355 - Checks urlencoded body params (_req.body_), ex: id=12

More docsTj Holowaychukbefore adoptiondfecbe5

lines 356–360why, one step back
356
357To utilize urlencoded request bodies, _req.body_358should be an object. This can be done by using359the _connect.bodyDecoder_ middleware.360

More docsTj Holowaychukbefore adoptionde81ee7

line 361why, one step back
361### req.flash(type[, msg])

More docsTj Holowaychukbefore adoptiondfecbe5

lines 362–378why, one step back
362
363Queue flash _msg_ of the given _type_.364365 req.flash('info', 'email sent');366 req.flash('error', 'email delivery failed');367 req.flash('info', 'email re-sent');368 // => 2369370 req.flash('info');371 // => ['email sent', 'email re-sent']372373 req.flash('info');374 // => []375376 req.flash();377 // => { error: ['email delivery failed'], info: [] }378

More docsTj Holowaychukbefore adoptionde81ee7

line 379why, one step back
379### req.isXMLHttpRequest

More docsTj Holowaychukbefore adoptiondfecbe5

lines 380–386why, one step back
380
381Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header382to see if it was issued by an _XMLHttpRequest_:383384 req.xhr385 req.isXMLHttpRequest386

More docsTj Holowaychukbefore adoptionde81ee7

line 387why, one step back
387### res.header(key[, val])

TasksTj Holowaychukbefore adoptiondf7582b

lines 388–399why, one step back
388
389Get or set the response header _key_.390391 res.header('Content-Length');392 // => undefined393394 res.header('Content-Length', 123);395 // => 123396397 res.header('Content-Length');398 // => 123399

More docsTj Holowaychukbefore adoptionde81ee7

line 400why, one step back
400### res.contentType(type)

TasksTj Holowaychukbefore adoptiondf7582b

lines 401–407why, one step back
401
402Sets the _Content-Type_ response header to the given _type_.403404 var filename = 'path/to/image.png';405 res.contentType(filename);406 // res.headers['Content-Type'] is now "image/png"407

More docsTj Holowaychukbefore adoptionde81ee7

line 408why, one step back
408### res.attachment([filename])

TasksTj Holowaychukbefore adoptiondf7582b

lines 409–413why, one step back
409
410Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.411412 res.attachment('path/to/my/image.png');413

More docsTj Holowaychukbefore adoptionde81ee7

line 414why, one step back
414### res.sendfile(path)

TasksTj Holowaychukbefore adoptiondf7582b

lines 415–419why, one step back
415
416Used by `res.download()` to transfer an arbitrary file. 417418 res.sendfile('path/to/my.file');419

Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1

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

TasksTj Holowaychukbefore adoptiondf7582b

line 424why, one step back
424

More docsTj Holowaychukbefore adoptionde81ee7

line 425why, one step back
425### res.download(file[, filename])

TasksTj Holowaychukbefore adoptiondf7582b

lines 426–436why, one step back
426
427Transfer the given _file_ as an attachment with optional alternative _filename_.428429 res.download('path/to/image.png');430 res.download('path/to/image.png', 'foo.png');431432This is equivalent to:433434 res.attachment(file);435 res.sendfile(file);436

More docsTj Holowaychukbefore adoptionde81ee7

line 437why, one step back
437### res.send(body|status[, headers|status[, status]])

TasksTj Holowaychukbefore adoptiondf7582b

lines 438–453why, one step back
438
439The `res.send()` method is a high level response utility allowing you to pass440objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status441code based responses. The following are all valid uses:442443 res.send(new Buffer('wahoo'));444 res.send({ some: 'json' });445 res.send('<p>some html</p>');446 res.send('Sorry, cant find that', 404);447 res.send('text', { 'Content-Type': 'text/plain' }, 201);448 res.send(404);449450By default the _Content-Type_ response header is set, however if explicitly451assigned through `res.send()` or previously with `res.header()` or `res.contentType()`452it will not be set again.453

More docsTj Holowaychukbefore adoptionde81ee7

line 454why, one step back
454### res.redirect(url[, status])

TasksTj Holowaychukbefore adoptiondf7582b

lines 455–467why, one step back
455
456Redirect to the given _url_ with a default response _status_ of 302.457458 res.redirect('/', 301);459 res.redirect('/account');460 res.redirect('http://google.com');461 res.redirect('home');462 res.redirect('back');463464Express supports "redirect mapping", which by default provides _home_, and _back_.465The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes466the "home" setting and defaults to "/".467

More view docsTj Holowaychukbefore adoption1c8ff48

lines 468–480why, one step back
468### res.render(view[, options[, fn]])
469470Render _view_ with the given _options_ and optional callback _fn_.471When a callback function is given a response will _not_ be made472automatically, however otherwise a response of _200_ and _text/html_ is given.473474 Most engines accept one or more of the following options,475 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:476477 - _context|scope_ Template evaluation context (_this_)478 - _locals_ Object containing local variables479 - _debug_ Output debugging information480

In depth partial docsTj Holowaychukbefore adoption793943f

lines 481–518why, one step back
481### res.partial(view[, options])
482483Render _view_ partial with the given _options_. This method is always available484to the view as a local variable.485486- _as_ Variable name for each _collection_ value, defaults to the view name.487 * as: 'something' will add the _something_ local variable488 * as: this will use the collection value as the template context489 * as: global will merge the collection value's properties with _locals_490491- _collection_ Array of objects, the name is derived from the view name itself. 492 For example _video.html_ will have a object _video_ available to it.493494The following are equivalent, and the name of collection value when passed495to the partial will be _movie_ as derived from the name.496497 partial('movie.jade', { collection: movies });498 partial('movie.jade', movies);499 partial('movie', movies);500 // In view: movie.director501502To change the local from _movie_ to _video_ we can use the "as" option:503504 partial('movie', { collection: movies, as: 'video' });505 // In view: video.director506507Also we can make our movie the value of _this_ within our view so that instead508of _movie.director_ we could use _this.director_.509510 partial('movie', { collection: movies, as: this });511 // In view: this.director512513Another alternative is to "explode" the properties of the collection item into514pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:515516 partials('movie', { collection: movies, as: global });517 // In view: director518

More docsTj Holowaychukbefore adoptionde81ee7

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

Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110

lines 524–526why, one step back
524 app.set('views', __dirname + '/views');
525 app.set('views');526 // => ...path...

More docsTj Holowaychukbefore adoptionde81ee7

lines 527–556why, one step back
527
528### app.enable(name)529530Enable the given setting _name_:531532 app.enable('some arbitrary setting');533 app.set('some arbitrary setting');534 // => true535536### app.disable(name)537538Disable the given setting _name_:539540 app.disable('some setting');541 app.set('some setting');542 // => false543544### app.configure(env|function[, function])545546Define a callback function for the given _env_ (or all environments) with callback _function_:547548 app.configure(function(){549 // executed for each env550 });551552 app.configure('development', function(){553 // executed for 'development' only554 });555556### app.redirect(name, val)

TasksTj Holowaychukbefore adoptiondf7582b

lines 557–567why, one step back
557
558For use with `res.redirect()` we can map redirects at the application level as shown below:559560 app.redirect('google', 'http://google.com');561562Now in a route we may call:563564 res.redirect('google');565566We may also map dynamic redirects:567

Updated docsTj Holowaychukbefore adoptiond691ecb

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

TasksTj Holowaychukbefore adoptiondf7582b

lines 570–578why, one step back
570 });
571572So now we may do the following, and the redirect will dynamically adjust to573the context of the request. If we called this route with _GET /post/12_ our574redirect _Location_ would be _/post/12/comments_.575576 app.get('/post/:id', function(req, res){577 res.redirect('comments');578 });

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 579–581why, one step back
579
580### app.error(function)581

More error docsTj Holowaychukbefore adoption6227f5c

lines 582–584why, one step back
582Adds an error handler _function_ which will receive the exception as the first parameter as shown below.
583Note that we may set several error handlers by making several calls to this method, however the handler584should call _next(err)_ if it does not wish to deal with the exception:

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 585–588why, one step back
585
586 app.error(function(err, req, res, next){587 res.send(err.message, 500);588 });

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 589–591why, one step back
589
590### app.helpers(obj)591

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

lines 592–607why, one step back
592Registers static view helpers.
593594 app.helpers({595 name: function(first, last){ return first + ', ' + last },596 firstName: 'tj',597 lastName: 'holowaychuk'598 });599600Our view could now utilize the _firstName_ and _lastName_ variables,601as well as the _name()_ function exposed.602603 <%= name(firstName, lastName) %>604605### app.dynamicHelpers(obj)606607Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

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

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 614–617why, one step back
614 return req.session;
615 }616 });617

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

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 621–634why, one step back
621
622### app.mounted(fn)623624Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.625626 var app = express.createServer(),627 blog = express.createServer();628 629 blog.mounted(function(parent){630 // parent is app631 // "this" is blog632 });633 634 app.use(blog);

Server#listen() docsTj Holowaychukbefore adoptionf3803c4

lines 635–643why, one step back
635
636### app.listen([port[, host]])637638Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all639connections will be accepted via _INADDR_ANY_.640641 app.listen();642 app.listen(3000);643 app.listen(3000, 'n.n.n.n');

Unix domain socket docsTj Holowaychukbefore adoption2fa7907

lines 644–658why, one step back
644
645The _port_ argument may also be a string representing the path to a unix domain socket:646647 app.listen('/tmp/express.sock');648649Then try it out:650651 $ telnet /tmp/express.sock652 GET / HTTP/1.1653654 HTTP/1.1 200 OK655 Content-Type: text/plain656 Content-Length: 11657 658 Hello World