Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,463 lines · 50.0 KiB · HTML

Last changed by

Route precondition docsTj Holowaychukbefore adoptionfd2f67b

History of this file

Take it

1<html>2	<head>3		<title>Express - node web framework</title>4		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>5		<style>6			#tagline {7			  margin-left: 75px;8			  margin-bottom: 30px;9			  color: rgba(255,255,255,0.7); }10			html {11			  background: #1c1c1c url(images/bg.tile.jpg); }1213			body {14			  margin: 0;15			  padding-bottom: 30px;16			  font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";17			  font-size: 14px;18			  line-height: 1.5;19			  -webkit-font-smoothing: antialiased;20			  background: url(images/bg.jpg) 50% 0 no-repeat;21			  color: #8b8b8b; }2223			* {24			  outline: none; }2526			em {27			  color: white; }2829			a img {30			  border: none !important; }3132			a {33			  font-weight: bold;34			  text-decoration: none;35			  color: white;36			  -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;37			  -webkit-transition-duration: 0.15s;38			  -webkit-transition-timing-function: ease-out; }39			  a:hover {40			    opacity: 0.8; }4142			h1, h2, h3, h4 {43			  margin: 45px 0 0 0;44			  color: white;45			  text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4647			h3 {48			  font-size: 18px; }49			h4 {50			  margin-left: 10px;51			  font-size: 14px;52			}5354			pre {55			  margin: 20px 10px;56			  padding: 25px 20px;57			  background: rgba(0,0,0,0.5);58			  border: 1px solid #323232;59			  -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);60			  -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61			  -webkit-border-radius: 5px;62			  -moz-border-radius: 5px; }6364			code {65			  font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6667			ul {68			  margin: 15px 0;69			  padding: 0 0 0 35px; }70			  ul li {71			    margin: 0;72			    padding: 2px 0;73			    list-style: square; }74          ul li ul {75            margin: 0;76            padding-left: 12px;77          }7879      .man-name, #Express { display:none; }8081			.sect {82			  margin-left: 40px; }83			img {84			  margin-left: 20px;85			  margin-bottom: 15px;86			}8788			#logo {89			  display: block;90			  margin-left: 30%;91			  margin-bottom: 30px;92			  width: 194px;93			  height: 51px;94			  background: url(images/logo.png) 0 0 no-repeat;95			  text-indent: -99999px; }96			  #logo:hover {97			    opacity: 0.7; }98			  #logo:active {99			    opacity: 0.3; }100101			#ribbon {102			  position: fixed;103			  top: 0;104			  right: 0;105			  z-index: 2; }106107			#wrapper {108			  width: 100%;109			  min-height: 800px;110			  background: url(images/top.png) 0 0 repeat-x; }111112			#container {113			  margin: 0 auto;114			  padding-top: 80px;115			  width: 550px; }116117			#toc {118				position: fixed;119				top: 0;120				left: 0;121				margin: 0 0 0 15px;122				padding: 15px;123				height: 100%;124				background: rgba(0,0,0,0.2);125				overflow: auto;126				border-right: 1px solid rgba(255,255,255,0.05);127			}128			#toc li {129				padding: 0;130				list-style: none;131			}132			#toc li a {133				font-size: 11px;134			}135			#menu {136			  margin-left: 75px;137			  padding: 0;138			  padding-bottom: 30px; }139			  #menu li {140			    display: inline;141			    list-style: none; }142			    #menu li a {143			      display: block;144			      float: left;145			      margin: 0 2px;146			      padding: 3px 15px;147			      background: rgba(0,0,0,0.2);148			      -webkit-border-radius: 8px;149			      -moz-border-radius: 8px;150			      -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);151			      -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152			      -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;153			      -webkit-transition-duration: 0.15s;154			      -webkit-transition-timing-function: ease-out; }155			      #menu li a:hover,156			      #menu li a.active {157			        background: rgba(0,0,0,0.5); }158			      #menu li a:active {159			        background: rgba(0,0,0,0.1);160			        -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);161			        -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }162		</style>163		<script>164		  $(function(){165		    $('.section').hide();166		    $('.toggle, a.section-title').toggle(function(){167		      $(this).siblings('ul').fadeIn(300);168		      return false;169		    }, function(){170		      $(this).siblings('ul').fadeOut(300);171		      return false;172		    });173		  });174		</script>175	</head>176	<body>177		<a href='http://github.com/visionmedia/express'> 178		  <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 179		</a>180		<div id="wrapper">181			<div id="container"><ul id="toc">182<li><a href="#Installation">Installation</a></li>183<li><a href="#Creating-An-Application">Creating An Application</a></li>184<li><a href="#Configuration">Configuration</a></li>185<li><a href="#Settings">Settings</a></li>186<li><a href="#Routing">Routing</a></li>187<li><a href="#Passing-Route-Control">Passing Route Control</a></li>188<li><a href="#Middleware">Middleware</a></li>189<li><a href="#Route-Middleware">Route Middleware</a></li>190<li><a href="#HTTP-Methods">HTTP Methods</a></li>191<li><a href="#Error-Handling">Error Handling</a></li>192<li><a href="#Route-Preconditions">Route Preconditions</a></li>193<li><a href="#View-Rendering">View Rendering</a></li>194<li><a href="#View-Partials">View Partials</a></li>195<li><a href="#Template-Engines">Template Engines</a></li>196<li><a href="#Session-Support">Session Support</a></li>197<li><a href="#Migration-Guide">Migration Guide</a></li>198<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">199<li><a href="#req-header-key-defaultValue-">header()</a></li>200<li><a href="#req-accepts-type-">accepts()</a></li>201<li><a href="#req-is-type-">is()</a></li>202<li><a href="#req-param-name-">param()</a></li>203<li><a href="#req-flash-type-msg-">flash()</a></li>204<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>205</ul></li>206<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">207<li><a href="#res-header-key-val-">header()</a></li>208<li><a href="#res-contentType-type-">contentType()</a></li>209<li><a href="#res-attachment-filename-">attachment()</a></li>210<li><a href="#res-sendfile-path-">sendfile()</a></li>211<li><a href="#res-download-file-filename-">download()</a></li>212<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>213<li><a href="#res-redirect-url-status-">redirect()</a></li>214<li><a href="#res-cookie-name-val-options-">cookie()</a></li>215<li><a href="#res-clearCookie-name-">clearCookie()</a></li>216<li><a href="#res-render-view-options-fn-">render()</a></li>217<li><a href="#res-partial-view-options-">partial()</a></li>218</ul></li>219<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">220<li><a href="#app-set-name-val-">set()</a></li>221<li><a href="#app-enable-name-">enable()</a></li>222<li><a href="#app-disable-name-">disable()</a></li>223<li><a href="#app-configure-env-function-function-">configure()</a></li>224<li><a href="#app-redirect-name-val-">redirect()</a></li>225<li><a href="#app-error-function-">error()</a></li>226<li><a href="#app-helpers-obj-">helpers()</a></li>227<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>228<li><a href="#app-mounted-fn-">mounted()</a></li>229<li><a href="#app-register-ext-exports-">register()</a></li>230<li><a href="#app-listen-port-host-">listen()</a></li>231</ul></li>232</ul>233				<a href='http://github.com/visionmedia/express' id='logo'>Express</a> 234				<p id="tagline">235				   High performance, high class web development for236				  <a href="http://nodejs.org">Node.js</a>237				</p>238				<ul id="menu">239					<li><a href="index.html">Home</a></li>240					<li><a href="guide.html">Guide</a></li>241					<li><a href="screencasts.html">Screencasts</a></li>242					<li><a href="applications.html">Applications</a></li>243				</ul>244<div class='mp'>245<h2 id="Express">Express</h2>246<p class="man-name">247  <code>guide</code>248</p>249<h3 id="Installation">Installation</h3>250251<p>curl:</p>252253<pre><code>$ curl -# http://expressjs.com/install.sh | sh254</code></pre>255256<p>npm:</p>257258<pre><code>$ npm install express259</code></pre>260261<h3 id="Creating-An-Application">Creating An Application</h3>262263<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however264follows the same idiom by providing <em>express.createServer()</em> as shown below. This means265that you can utilize Express server's transparently with other libraries.</p>266267<pre><code>var app = require('express').createServer();268269app.get('/', function(req, res){270    res.send('hello world');271});272273app.listen(3000);274</code></pre>275276<h3 id="Configuration">Configuration</h3>277278<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers279can use the <em>configure()</em> method to setup needs required by the current environment. When280<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment281prior to the environment specific callback.</p>282283<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces284in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.285Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,286otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>287288<pre><code>app.configure(function(){289    app.use(express.methodOverride());290    app.use(express.bodyDecoder());291    app.use(app.router);292    app.use(express.staticProvider(__dirname + '/public'));293});294295app.configure('development', function(){296    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));297});298299app.configure('production', function(){300    app.use(express.errorHandler());301});302</code></pre>303304<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>305306<pre><code>app.configure(function(){307    app.set('views', __dirname + '/views');308    app.set('views');309    // =&gt; "... views directory ..."310311    app.enable('some feature');312    // same as app.set('some feature', true);313314    app.disable('some feature');315    // same as app.set('some feature', false);316});317</code></pre>318319<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>320321<pre><code>$ NODE_ENV=production node app.js322</code></pre>323324<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>325326<h3 id="Settings">Settings</h3>327328<p>Express supports the following settings out of the box:</p>329330<ul>331<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>332<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>333<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>334<li><em>view engine</em> Default view engine name for views rendered without extensions</li>335<li><em>view options</em> An object specifying global view options</li>336<li><em>stream threshold</em> Bytesize indicating when a file should be streamed for <em>res.sendfile()</em> using <em>fs.ReadStream()</em> and <em>sys.pump()</em>.</li>337</ul>338339340<h3 id="Routing">Routing</h3>341342<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.343For example we may want to render a user's account for the path <em>/user/12</em>, this344can be done by defining the route below. The values associated to the named placeholders345are available as <code>req.params</code>.</p>346347<pre><code>app.get('/user/:id', function(req, res){348    res.send('user ' + req.params.id);349});350</code></pre>351352<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example353when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>354355<pre><code>\/user\/([^\/]+)\/?356</code></pre>357358<p>Regular expression literals may also be passed for complex uses. Since capture359groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>. So our first capture group would be <em>req.params[0]</em> and the second would follow as <em>req.params[1]</em>.</p>360361<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){362    res.send(req.params);363});364</code></pre>365366<p>Curl requests against the previously defined route:</p>367368<pre><code>   $ curl http://dev:3000/user369   [null,null]370   $ curl http://dev:3000/users371   [null,null]372   $ curl http://dev:3000/users/1373   ["1",null]374   $ curl http://dev:3000/users/1..15375   ["1","15"]376</code></pre>377378<p>Below are some route examples, and the associated paths that they379may consume:</p>380381<pre><code> "/user/:id"382 /user/12383384 "/users/:id?"385 /users/5386 /users387388 "/files/*"389 /files/jquery.js390 /files/javascripts/jquery.js391392 "/file/*.*"393 /files/jquery.js394 /files/javascripts/jquery.js395396 "/user/:id/:operation?"397 /user/1398 /user/1/edit399400 "/products.:format"401 /products.json402 /products.xml403404 "/products.:format?"405 /products.json406 /products.xml407 /products408409 "/user/:id.:format?"410 /user/12411 /user/12.json412</code></pre>413414<p>For example we can <strong>POST</strong> some json, and echo the json back using the <em>bodyDecoder</em> middleware which will parse json request bodies (as well as others), and place the result in <em>req.body</em>:</p>415416<pre><code>var express = require('express')417  , app = express.createServer();418419app.use(express.bodyDecoder());420421app.post('/', function(req, res){422  res.send(req.body);423});424425app.listen(3000);426</code></pre>427428<p>Express 2.0.0-pre also supports named capture groups. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, however say for example we are limiting a user id to digits, we may use <em>'/user/:id(\d+)'</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>429430<h3 id="Passing-Route-Control">Passing Route Control</h3>431432<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,433the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,434and middleware continue to be invoked. The same is true for several routes which have the same path defined, they will simply be executed in order until one does <em>not</em> call <em>next()</em>.</p>435436<pre><code>app.get('/users/:id?', function(req, res, next){437    var id = req.params.id;438    if (id) {439        // do something440    } else {441        next();442    }443});444445app.get('/users', function(req, res){446    // do something else447});448</code></pre>449450<p>Express 1.0 also introduces the <em>all()</em> method, which provides a route callback matching any HTTP method. This is useful in many ways, one example being the loading of resources before executing subsequent routes as shown below:</p>451452<pre><code>var express = require('express')453  , app = express.createServer();454455var users = [{ name: 'tj' }];456457app.all('/user/:id/:op?', function(req, res, next){458  req.user = users[req.params.id];459  if (req.user) {460    next();461  } else {462    next(new Error('cannot find user ' + req.params.id));463  }464});465466app.get('/user/:id', function(req, res){467  res.send('viewing ' + req.user.name);468});469470app.get('/user/:id/edit', function(req, res){471  res.send('editing ' + req.user.name);472});473474app.put('/user/:id', function(req, res){475  res.send('updating ' + req.user.name);476});477478app.get('*', function(req, res){479  res.send('what???', 404);480});481482app.listen(3000); 483</code></pre>484485<h3 id="Middleware">Middleware</h3>486487<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be488passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>489490<pre><code>  var express = require('express');491492var app = express.createServer(493    express.logger(),494    express.bodyDecoder()495  );496</code></pre>497498<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>499500<pre><code>app.use(express.logger({ format: ':method :uri' }));501</code></pre>502503<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>504505<pre><code>var connect = require('connect');506app.use(connect.logger());507</code></pre>508509<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>510511<pre><code>app.use(express.logger());512</code></pre>513514<h3 id="Route-Middleware">Route Middleware</h3>515516<p>Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.</p>517518<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>519520<pre><code>app.get('/user/:id', function(req, res, next){521    loadUser(req.params.id, function(err, user){522        if (err) return next(err);523        res.send('Viewing user ' + user.name);524    });525});526</code></pre>527528<p>To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time.</p>529530<pre><code>function loadUser(req, res, next) {531    // You would fetch your user from the db532    var user = users[req.params.id];533    if (user) {534        req.user = user;535        next();536    } else {537        next(new Error('Failed to load user ' + req.params.id));538    }539}540541app.get('/user/:id', loadUser, function(req, res){542    res.send('Viewing user ' + req.user.name);543});544</code></pre>545546<p>Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.</p>547548<pre><code>function andRestrictToSelf(req, res, next) {549    req.authenticatedUser.id == req.user.id550        ? next()551        : next(new Error('Unauthorized'));552}553554app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){555    res.send('Editing user ' + req.user.name);556});557</code></pre>558559<p>Keeping in mind that middleware are simply functions, we can define function that <em>returns</em> the middleware in order to create a more expressive and flexible solution as shown below.</p>560561<pre><code>function andRestrictTo(role) {562    return function(req, res, next) {563      req.authenticatedUser.role == role564          ? next()565          : next(new Error('Unauthorized'));566    }567}568569app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){570    res.send('Deleted user ' + req.user.name);571});572</code></pre>573574<p>Commonly used "stacks" of middleware can be passed as an array (<em>applied recursively</em>), which can be mixed and matched to any degree.</p>575576<pre><code>var a = [middleware1, middleware2]577  , b = [middleware3, middleware4]578  , all = [a, b];579580app.get('/foo', a, function(){});581app.get('/bar', a, function(){});582583app.get('/', a, middleware3, middleware4, function(){});584app.get('/', a, b, function(){});585app.get('/', all, function(){});586</code></pre>587588<p>For this example in full, view the <a href="http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js">route middleware example</a> in the repository.</p>589590<h3 id="HTTP-Methods">HTTP Methods</h3>591592<p>We have seen <em>app.get()</em> a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as <em>app.post()</em>, <em>app.del()</em>, etc.</p>593594<p> A common example for <em>POST</em> 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.</p>595596<pre><code> &lt;form method="post" action="/"&gt;597     &lt;input type="text" name="user[name]" /&gt;598     &lt;input type="text" name="user[email]" /&gt;599     &lt;input type="submit" value="Submit" /&gt;600 &lt;/form&gt;601</code></pre>602603<p>By default Express does not know what to do with this request body, so we should add the <em>bodyDecoder</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>604605<pre><code>app.use(express.bodyDecoder());606</code></pre>607608<p>Our route below will now have access to the <em>req.body.user</em> object which will contain the <em>name</em> and <em>email</em> properties when defined.</p>609610<pre><code>app.post('/', function(req, res){611    console.log(req.body.user);612    res.redirect('back');613});614</code></pre>615616<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyDecoder</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>617618<pre><code>app.use(express.bodyDecoder());619app.use(express.methodOverride());620</code></pre>621622<p>The 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 <em>PUT</em> and <em>DELETE</em> can still be accessed by clients which can use them directly, although <em>methodOverride</em> provides a great solution for forms. Below shows what the usage of <em>PUT</em> might look like:</p>623624<pre><code>&lt;form method="post" action="/"&gt;625  &lt;input type="hidden" name="_method" value="put" /&gt;626  &lt;input type="text" name="user[name]" /&gt;627  &lt;input type="text" name="user[email]" /&gt;628  &lt;input type="submit" value="Submit" /&gt;    629&lt;/form&gt;630631app.put('/', function(){632    console.log(req.body.user);633    res.redirect('back');634});635</code></pre>636637<h3 id="Error-Handling">Error Handling</h3>638639<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,640or passed to <em>next(err)</em>. Below is an example which serves different pages based on our641ad-hoc <em>NotFound</em> exception:</p>642643<pre><code>function NotFound(msg){644    this.name = 'NotFound';645    Error.call(this, msg);646    Error.captureStackTrace(this, arguments.callee);647}648649sys.inherits(NotFound, Error);650651app.get('/404', function(req, res){652    throw new NotFound;653});654655app.get('/500', function(req, res){656    throw new Error('keyboard cat!');657});658</code></pre>659660<p>We can call <em>app.error()</em> several times as shown below.661Here we check for an instanceof <em>NotFound</em> and show the662404 page, or we pass on to the next error handler.</p>663664<p>Note that these handlers can be defined anywhere, as they665will be placed below the route handlers on <em>listen()</em>. This666allows for definition within <em>configure()</em> blocks so we can667handle exceptions in different ways based on the environment.</p>668669<pre><code>app.error(function(err, req, res, next){670    if (err instanceof NotFound) {671        res.render('404.jade');672    } else {673        next(err);674    }675});676</code></pre>677678<p>Here we assume all errors as 500 for the simplicity of679this demo, however you can choose whatever you like</p>680681<pre><code>app.error(function(err, req, res){682    res.render('500.jade', {683       locals: {684           error: err685       } 686    });687});688</code></pre>689690<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware691to report on exceptions. For example if we wish to output exceptions692in "development" mode to <em>stderr</em> we can use:</p>693694<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));695</code></pre>696697<p>Also during development we may want fancy html pages to show exceptions698that are passed or thrown, so we can set <em>showStack</em> to true:</p>699700<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));701</code></pre>702703<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>704is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>705706<h3 id="Route-Preconditions">Route Preconditions</h3>707708<p>Route placeholder pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for <em>/user/:id</em>,we might typically do something like below:</p>709710<pre><code>app.get('/user/:userId', function(req, res, next){711  User.get(req.params.userId, function(err, user){712    if (err) return next(err);713    res.send('user ' + user.name);714  });715}); 716</code></pre>717718<p>With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>719720<pre><code>app.param('userId', function(req, res, next, id){721  User.get(id, function(err, user){722    if (err) return next(err);723    if (!user) return next(new Error('failed to find user'));724    req.user = user;725    next();726  });727});728</code></pre>729730<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>731732<pre><code>app.get('/user/:userId', function(req, res){733  res.send('user ' + req.user.name);734});735</code></pre>736737<p>For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to <em>next(err)</em>.</p>738739<pre><code>app.param('number', function(n){ return parseInt(n, 10); });740</code></pre>741742<p>We may also apply the same callback to several placeholders, for example a route GET <em>/commits/:from-:to</em> are both numbers, so we may define them as an array:</p>743744<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });745</code></pre>746747<h3 id="View-Rendering">View Rendering</h3>748749<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name750of the module that will be required. For example the view <em>layout.ejs</em> will751tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.render(str, options)</em> to comply with Express, however752<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.</p>753754<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,755and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as756the <em>body</em> local variable in <em>layout.haml</em>.</p>757758<pre><code>app.get('/', function(req, res){759    res.render('index.haml', {760        locals: { title: 'My Site' }761    });762});763</code></pre>764765<p>The new <em>view engine</em> setting allows us to specify our default template engine,766so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>767768<pre><code>app.set('view engine', 'jade');769</code></pre>770771<p>Allowing us to render with:</p>772773<pre><code>res.render('index');774</code></pre>775776<p>vs:</p>777778<pre><code>res.render('index.jade');779</code></pre>780781<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still782mix and match template engines:</p>783784<pre><code>res.render('another-page.ejs');785</code></pre>786787<p>Express also provides the <em>view options</em> setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:</p>788789<pre><code>app.set('view options', {790    layout: false791});792</code></pre>793794<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>795796<pre><code>res.render('myview.ejs', { layout: true });797</code></pre>798799<p>When an alternate layout is required, we may also specify a path. For example if we have <em>view engine</em> set to <em>jade</em> and a file named <em>./views/mylayout.jade</em> we can simply pass:</p>800801<pre><code>res.render('page', { layout: 'mylayout' });802</code></pre>803804<p>Otherwise we must specify the extension:</p>805806<pre><code>res.render('page', { layout: 'mylayout.jade' });807</code></pre>808809<p>These paths may also be absolute:</p>810811<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });812</code></pre>813814<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>815816<pre><code>app.set('view options', {817    open: '{{',818    close: '}}'819});820</code></pre>821822<h3 id="View-Partials">View Partials</h3>823824<p>The Express view system has built-in support for partials and collections, which are825sort of "mini" views representing a document fragment. For example rather than iterating826in a view to display comments, we would use a partial with collection support:</p>827828<pre><code>partial('comment.haml', { collection: comments });829</code></pre>830831<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,832however if we wished we could use an ejs partial, within a haml view for example.</p>833834<pre><code>partial('comment', { collection: comments });835</code></pre>836837<p>And once again even further, when rendering a collection we can simply pass838an array, if no other options are desired:</p>839840<pre><code>partial('comment', comments);841</code></pre>842843<p>When using the partial collection support a few "magic" variables are provided844for free:</p>845846<ul>847<li><em>firstInCollection</em>  True if this is the first object</li>848<li><em>indexInCollection</em>  Index of the object in the collection</li>849<li><em>lastInCollection</em>  True if this is the last object</li>850<li><em>collectionLength</em>  Length of the collection</li>851</ul>852853854<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>855856<p>NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead. For example do <em>not</em> implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates.</p>857858<h3 id="Template-Engines">Template Engines</h3>859860<p>Below are a few template engines commonly used with Express:</p>861862<ul>863<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>864<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>865<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>866<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>867<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>868</ul>869870871<h3 id="Session-Support">Session Support</h3>872873<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieDecoder</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>874875<pre><code>app.use(express.cookieDecoder());876app.use(express.session());877</code></pre>878879<p>By default the <em>session</em> middleware uses the memory store bundled with Connect, however many implementations exist. For example <a href="http://github.com/visionmedia/connect-redis">connect-redis</a> supplies a <a href="http://code.google.com/p/redis/">Redis</a> session store and can be used as shown below:</p>880881<pre><code>var RedisStore = require('connect-redis');882app.use(express.cookieDecoder());883app.use(express.session({ store: new RedisStore }));884</code></pre>885886<p>Now the <em>req.session</em> and <em>req.sessionStore</em> properties will be accessible to all routes and subsequent middleware. Properties on <em>req.session</em> are automatically saved on a response, so for example if we wish to shopping cart data:</p>887888<pre><code>var RedisStore = require('connect-redis');889app.use(express.bodyDecoder());890app.use(express.cookieDecoder());891app.use(express.session({ store: new RedisStore }));892893app.post('/add-to-cart', function(req, res){894  // Perhaps we posted several items with a form895  // (use the bodyDecoder() middleware for this)896  var items = req.body.items;897  req.session.items = items;898  res.redirect('back');899});900901app.get('/add-to-cart', function(req, res){902  // When redirected back to GET /add-to-cart903  // we could check req.session.items &amp;&amp; req.session.items.length904  // to print out a message905  if (req.session.items &amp;&amp; req.session.items.length) {906    req.flash('info', 'You have %s items in your cart', req.session.items.length);907  }908  res.render('shopping-cart');909});910</code></pre>911912<p>The <em>req.session</em> object also has methods such as <em>Session#touch()</em>, <em>Session#destroy()</em>, <em>Session#regenerate()</em> among others to maintain and manipulate sessions. For more information view the <a href="http://senchalabs.github.com/connect/session.html">Connect Session</a> documentation.</p>913914<h3 id="Migration-Guide">Migration Guide</h3>915916<p> Pre-beta Express developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application.</p>917918<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>919920<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>921922<pre><code>req.header('Host');923req.header('host');924req.header('Accept', '*/*');925</code></pre>926927<h3 id="req-accepts-type-">req.accepts(type)</h3>928929<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>930931<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise932the given <em>type</em> is matched by an exact match, and then subtypes. You933may pass the subtype such as "html" which is then converted internally934to "text/html" using the mime lookup table.</p>935936<pre><code>// Accept: text/html937req.accepts('html');938// =&gt; true939940// Accept: text/*; application/json941req.accepts('html');942req.accepts('text/html');943req.accepts('text/plain');944req.accepts('application/json');945// =&gt; true946947req.accepts('image/png');948req.accepts('png');949// =&gt; false950</code></pre>951952<h3 id="req-is-type-">req.is(type)</h3>953954<p>Check if the incoming request contains the <em>Content-Type</em>955header field, and it contains the give mime <em>type</em>.</p>956957<pre><code>   // With Content-Type: text/html; charset=utf-8958   req.is('html');959   req.is('text/html');960   // =&gt; true961962   // When Content-Type is application/json963   req.is('json');964   req.is('application/json');965   // =&gt; true966967   req.is('html');968   // =&gt; false969</code></pre>970971<p>Ad-hoc callbacks can also be registered with Express, to perform972assertions again the request, for example if we need an expressive973way to check if our incoming request is an image, we can register <em>"an image"</em>974callback:</p>975976<pre><code>    app.is('an image', function(req){977      return 0 == req.headers['content-type'].indexOf('image');978    });979</code></pre>980981<p>Now within our route callbacks, we can use to to assert content types982such as <em>"image/jpeg"</em>, <em>"image/png"</em>, etc.</p>983984<pre><code>   app.post('/image/upload', function(req, res, next){985     if (req.is('an image')) {986       // do something987     } else {988       next();989     }990   });991</code></pre>992993<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you994can perform any request assertion you wish.</p>995996<p>Wildcard matches can also be made, simplifying our example above for <em>"an image"</em>, by asserting the <em>subtype</em> only:</p>997998<pre><code>req.is('image/*');999</code></pre>10001001<p>We may also assert the <em>type</em> as shown below, which would return true for <em>"application/json"</em>, and <em>"text/json"</em>.</p>10021003<pre><code>req.is('*/json');1004</code></pre>10051006<h3 id="req-param-name-">req.param(name)</h3>10071008<p>Return the value of param <em>name</em> when present.</p>10091010<ul>1011<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>1012<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1013<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1014</ul>101510161017<p>To utilize urlencoded request bodies, <em>req.body</em>1018should be an object. This can be done by using1019the <em>express.bodyDecoder</em> middleware.</p>10201021<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>10221023<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>10241025<pre><code>req.flash('info', 'email sent');1026req.flash('error', 'email delivery failed');1027req.flash('info', 'email re-sent');1028// =&gt; 210291030req.flash('info');1031// =&gt; ['email sent', 'email re-sent']10321033req.flash('info');1034// =&gt; []10351036req.flash();1037// =&gt; { error: ['email delivery failed'], info: [] }1038</code></pre>10391040<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>10411042<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1043</code></pre>10441045<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>10461047<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1048to see if it was issued by an <em>XMLHttpRequest</em>:</p>10491050<pre><code>req.xhr1051req.isXMLHttpRequest1052</code></pre>10531054<h3 id="res-header-key-val-">res.header(key[, val])</h3>10551056<p>Get or set the response header <em>key</em>.</p>10571058<pre><code>res.header('Content-Length');1059// =&gt; undefined10601061res.header('Content-Length', 123);1062// =&gt; 12310631064res.header('Content-Length');1065// =&gt; 1231066</code></pre>10671068<h3 id="res-contentType-type-">res.contentType(type)</h3>10691070<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>10711072<pre><code>  var filename = 'path/to/image.png';1073  res.contentType(filename);1074  // res.headers['Content-Type'] is now "image/png"1075</code></pre>10761077<h3 id="res-attachment-filename-">res.attachment([filename])</h3>10781079<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>10801081<pre><code>  res.attachment('path/to/my/image.png');1082</code></pre>10831084<h3 id="res-sendfile-path-">res.sendfile(path)</h3>10851086<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>10871088<pre><code>res.sendfile('path/to/my.file');1089</code></pre>10901091<p>This 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 <strong>not</strong> been streamed, <em>next(err)</em> will be called on an exception.</p>10921093<pre><code>res.sendfile(path, function(err, path){1094  if (err) {1095    // handle the error1096  } else {1097    console.log('transferred %s', path);1098  }1099});1100</code></pre>11011102<p>When the filesize exceeds the <em>stream threshold</em> (defaulting to 32k), the file will be streamed using <em>fs.ReadStream</em> and <em>sys.pump()</em>.</p>11031104<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>11051106<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>11071108<pre><code>res.download('path/to/image.png');1109res.download('path/to/image.png', 'foo.png');1110</code></pre>11111112<p>This is equivalent to:</p>11131114<pre><code>res.attachment(file);1115res.sendfile(file);1116</code></pre>11171118<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>11191120<p>The <code>res.send()</code> method is a high level response utility allowing you to pass1121objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status1122code based responses. The following are all valid uses:</p>11231124<pre><code> res.send(); // 2041125 res.send(new Buffer('wahoo'));1126 res.send({ some: 'json' });1127 res.send('&lt;p&gt;some html&lt;/p&gt;');1128 res.send('Sorry, cant find that', 404);1129 res.send('text', { 'Content-Type': 'text/plain' }, 201);1130 res.send(404);1131</code></pre>11321133<p>By default the <em>Content-Type</em> response header is set, however if explicitly1134assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1135it will not be set again.</p>11361137<p>Note that this method <em>end()</em> the response, so you will want to use node's <em>res.writeHead()</em> / <em>res.write()</em> for multiple writes or streaming.</p>11381139<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>11401141<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>11421143<pre><code>res.redirect('/', 301);1144res.redirect('/account');1145res.redirect('http://google.com');1146res.redirect('home');1147res.redirect('back');1148</code></pre>11491150<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1151The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1152the "home" setting and defaults to "/".</p>11531154<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>11551156<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>11571158<pre><code>// "Remember me" for 15 minutes 1159res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1160</code></pre>11611162<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>11631164<pre><code>app.use(express.cookieDecoder());11651166app.get('/', function(req, res){1167    // use req.cookies.rememberme1168});1169</code></pre>11701171<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>11721173<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>11741175<pre><code>res.clearCookie('rememberme');1176</code></pre>11771178<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>11791180<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1181When a callback function is given a response will <em>not</em> be made1182automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>11831184<p> Most engines accept one or more of the following options,1185 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>11861187<ul>1188<li><em>scope</em>           Template evaluation context (value of <em>this</em>)</li>1189<li><em>locals</em>          Object containing local variables</li>1190<li><em>debug</em>           Output debugging information</li>1191<li><em>status</em>          Response status code, defaults to 200</li>1192<li><em>headers</em>         Response headers object</li>1193</ul>119411951196<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>11971198<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1199to the view as a local variable.</p>12001201<ul>1202<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1203<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>12041205<ul>1206<li>as: 'something' will add the <em>something</em> local variable</li>1207<li>as: this will use the collection value as the template context</li>1208<li>as: global will merge the collection value's properties with <em>locals</em></li>1209</ul>1210</li>1211<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1212For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1213</ul>121412151216<p>The following are equivalent, and the name of collection value when passed1217to the partial will be <em>movie</em> as derived from the name.</p>12181219<pre><code>partial('theatre/movie.jade', { collection: movies });1220partial('theatre/movie.jade', movies);1221partial('movie.jade', { collection: movies });1222partial('movie.jade', movies);1223partial('movie', movies);1224// In view: movie.director1225</code></pre>12261227<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>12281229<pre><code>partial('movie', { collection: movies, as: 'video' });1230// In view: video.director1231</code></pre>12321233<p>Also we can make our movie the value of <em>this</em> within our view so that instead1234of <em>movie.director</em> we could use <em>this.director</em>.</p>12351236<pre><code>partial('movie', { collection: movies, as: this });1237// In view: this.director1238</code></pre>12391240<p>Another alternative is to "explode" the properties of the collection item into1241pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>12421243<pre><code>partial('movie', { collection: movies, as: global });1244// In view: director1245</code></pre>12461247<p>This same logic applies to a single partial object usage:</p>12481249<pre><code>partial('movie', { object: movie, as: this });1250// In view: this.director12511252partial('movie', { object: movie, as: global });1253// In view: director12541255partial('movie', { object: movie, as: 'video' });1256// In view: video.director12571258partial('movie', { object: movie });1259// In view: movie.director1260</code></pre>12611262<p>When a non-collection (does <em>not</em> have <em>.length</em>) is passed as the second argument, it is assumed to be the <em>object</em>, after which the object's local variable name is derived from the view name:</p>12631264<pre><code>partial('movie', movie);1265// =&gt; In view: movie.director1266</code></pre>12671268<h3 id="app-set-name-val-">app.set(name[, val])</h3>12691270<p>Apply an application level setting <em>name</em> to <em>val</em>, or1271get the value of <em>name</em> when <em>val</em> is not present:</p>12721273<pre><code>app.set('views', __dirname + '/views');1274app.set('views');1275// =&gt; ...path...1276</code></pre>12771278<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>12791280<pre><code>app.settings.views1281// =&gt; ...path...1282</code></pre>12831284<h3 id="app-enable-name-">app.enable(name)</h3>12851286<p>Enable the given setting <em>name</em>:</p>12871288<pre><code>app.enable('some arbitrary setting');1289app.set('some arbitrary setting');1290// =&gt; true1291</code></pre>12921293<h3 id="app-disable-name-">app.disable(name)</h3>12941295<p>Disable the given setting <em>name</em>:</p>12961297<pre><code>app.disable('some setting');1298app.set('some setting');1299// =&gt; false1300</code></pre>13011302<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>13031304<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>13051306<pre><code>app.configure(function(){1307    // executed for each env1308});13091310app.configure('development', function(){1311    // executed for 'development' only1312});1313</code></pre>13141315<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>13161317<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>13181319<pre><code>app.redirect('google', 'http://google.com');1320</code></pre>13211322<p>Now in a route we may call:</p>13231324<p>   res.redirect('google');</p>13251326<p>We may also map dynamic redirects:</p>13271328<pre><code>app.redirect('comments', function(req, res){1329    return '/post/' + req.params.id + '/comments';1330});1331</code></pre>13321333<p>So now we may do the following, and the redirect will dynamically adjust to1334the context of the request. If we called this route with <em>GET /post/12</em> our1335redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>13361337<pre><code>app.get('/post/:id', function(req, res){1338    res.redirect('comments');1339});1340</code></pre>13411342<h3 id="app-error-function-">app.error(function)</h3>13431344<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1345Note that we may set several error handlers by making several calls to this method, however the handler1346should call <em>next(err)</em> if it does not wish to deal with the exception:</p>13471348<pre><code>app.error(function(err, req, res, next){1349    res.send(err.message, 500);1350});1351</code></pre>13521353<h3 id="app-helpers-obj-">app.helpers(obj)</h3>13541355<p>Registers static view helpers.</p>13561357<pre><code>app.helpers({1358    name: function(first, last){ return first + ', ' + last },1359    firstName: 'tj',1360    lastName: 'holowaychuk'1361});1362</code></pre>13631364<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1365as well as the <em>name()</em> function exposed.</p>13661367<pre><code>&lt;%= name(firstName, lastName) %>1368</code></pre>13691370<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>13711372<p>Registers dynamic view helpers. Dynamic view helpers1373are simply functions which accept <em>req</em>, <em>res</em>, and are1374evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1375becomes the local variable it is associated with.</p>13761377<pre><code>app.dynamicHelpers({1378    session: function(req, res){1379        return req.session;1380    }1381});1382</code></pre>13831384<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>13851386<pre><code>&lt;%= session.name %&gt;1387</code></pre>13881389<h3 id="app-mounted-fn-">app.mounted(fn)</h3>13901391<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>13921393<pre><code>var app = express.createServer(),1394    blog = express.createServer();13951396blog.mounted(function(parent){1397    // parent is app1398    // "this" is blog1399});14001401app.use(blog);1402</code></pre>14031404<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>14051406<p>Register the given template engine <em>exports</em>1407as <em>ext</em>. For example we may wish to map ".html"1408files to jade:</p>14091410<pre><code> app.register('.html', require('jade'));1411</code></pre>14121413<p>This is also useful for libraries that may not1414match extensions correctly. For example my haml.js1415library is installed from npm as "hamljs" so instead1416of layout.hamljs, we can register the engine as ".haml":</p>14171418<pre><code> app.register('.haml', require('haml-js'));1419</code></pre>14201421<p>For engines that do not comply with the Express1422specification, we can also wrap their api this way.</p>14231424<pre><code> app.register('.foo', {1425     render: function(str, options) {1426         // perhaps their api is1427         // return foo.toHTML(str, options);1428     }1429 });1430</code></pre>14311432<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>14331434<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1435connections will be accepted via <em>INADDR_ANY</em>.</p>14361437<pre><code>app.listen();1438app.listen(3000);1439app.listen(3000, 'n.n.n.n');1440</code></pre>14411442<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>14431444<pre><code>app.listen('/tmp/express.sock');1445</code></pre>14461447<p>Then try it out:</p>14481449<pre><code>$ telnet /tmp/express.sock1450GET / HTTP/1.114511452HTTP/1.1 200 OK1453Content-Type: text/plain1454Content-Length: 1114551456Hello World1457</code></pre>14581459</div>1460			</div>1461		</div>1462	</body>1463</html>