regenerated docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent eefe51c · Browse files · 15 files·+351 added−3244 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+351 added−3244 removed
- other:+351 added−3244 removed
Provenance
- Commit
dd7158a- Tree
14fa894- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
eefe51c
15 files changed+351 added−3244 removed
deleted:docs/applications.1-70 removed
1-.\" generated with Ronn/v0.7.32-.\" http://github.com/rtomayko/ronn/tree/0.7.33-.4-.TH "APPLICATIONS" "" "March 2011" "" ""5-.6-.SH "NAME"7-\fBapplications\fR8-.9-.P10-Learnboost \fIhttp://learnboost\.com\fR is a free online gradebook application, aimed to crush the competition with innovative, realtime, enjoyable features\.11-.12-.P13- \fIhttp://learnboost\.com\fR14-.15-.P16-Storify \fIhttp://storify\.com\fR lets you turn what people post on social media websites into compelling stories\.17-.18-.P19- \fIhttp://storify\.com\fR20-.21-.P22-Pakistan Survey \fIhttp://pakistansurvey\.org/\fR by Development Seed \fIhttp://developmentseed\.org\fR, provides in\-depth agency\-specific analysis from regional experts with data from 1,000 interviews across 120 villages in all seven tribal agencies and mapping of 142 reported drone strikes in FATA through July 2010\.23-.24-.P25- \fIhttp://pakistansurvey\.org\fR26-.27-.P28-Markup\.IO \fIhttp://markup\.io\fR allows you to draw directly on \fIany\fR website, then share with others to share your thoughts\.29-.30-.P31- \fIhttp://markup\.io\fR32-.33-.P34-Scrabb\.ly \fIhttp://scrabb\.ly\fR is a massively multiplayer scrabble game initially created for the Node Knockout \fIhttp://nodeknockout\.com/\fR competition\.35-.36-.P37- \fIhttp://scrabb\.ly\fR38-.39-.P40-ClickDummy \fIhttp://clickdummy\.net/\fR is a rapid mockup prototyping application for designers and dummies\.41-.42-.P43- \fIhttp://clickdummy\.net\fR44-.45-.P46-Node Knockout \fIhttp://nodeknockout\.com\fR organized the first ever node\-specific competition with hundreds of contestants\.47-.48-.P49- \fIhttp://nodeknockout\.com\fR50-.51-.P52-Widescript \fIhttp://widescript\.com\fR is an innovative app that helps you focus and interact with your texts \- on your desktop, your couch or on the go\.53-.54-.P55- \fIhttp://widescript\.com\fR56-.57-.P58-e\-resistable \fIhttp://www\.e\-resistible\.co\.uk/\fR is an online order takeaway system providing an intuitive way to fill your belly from your computer!59-.60-.P61- \fIhttp://www\.e\-resistible\.co\.uk\fR62-.63-.P64-Top Twitter Trends \fIhttp://toptwittertrends\.com\fR utilizes MongoDB, Socket\.IO, jQuery and many other exciting libraries to bring you trending tweets in realtime\.65-.66-.P67- \fIhttp://toptwittertrends\.com\fR68-.69-.P70-The applications shown above are not listed in any specific order\. To have an application added or removed please contact TJ Holowaychuk \fIhttp://github\.com/visionmedia\fR\.modified:docs/applications.html+12 added-23 removed
188 unmodified lines189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193-<div class='mp'>194-<h2 id="Express">Express</h2>195-<p class="man-name">196- <code>applications</code>197-</p>193+<p><br /></p>194 199-200-<br />201-202-195 <p><a href="http://learnboost.com">Learnboost</a> is a free online gradebook application, aimed to crush the competition with innovative, realtime, enjoyable features.</p>196 205-<p><a href="http://learnboost.com"><img src="images/apps/learnboost.png" alt="LearnBoost" /></a></p>197+<p>[<img alt="LearnBoost" src="images/apps/learnboost.png)](http://learnboost.com" /></p>198 199 <p><a href="http://storify.com">Storify</a> lets you turn what people post on social media websites into compelling stories.</p>200 209-<p><a href="http://storify.com"><img src="images/apps/storify.png" alt="Storify" /></a></p>201+<p>[<img alt="Storify" src="images/apps/storify.png)](http://storify.com" /></p>202 203 <p><a href="http://pakistansurvey.org/">Pakistan Survey</a> by <a href="http://developmentseed.org">Development Seed</a>, provides in-depth agency-specific analysis from regional experts with data from 1,000 interviews across 120 villages in all seven tribal agencies and mapping of 142 reported drone strikes in FATA through July 2010.</p>204 213-<p><a href="http://pakistansurvey.org"><img src="images/apps/developmentseed.png" alt="Pakistan Survey" /></a></p>205+<p>[<img alt="Pakistan Survey" src="images/apps/developmentseed.png)](http://pakistansurvey.org" /></p>206 207 <p><a href="http://markup.io">Markup.IO</a> allows you to draw directly on <em>any</em> website, then share with others to share your thoughts.</p>208 217-<p><a href="http://markup.io"><img src="images/apps/markupio.png" alt="Markup.IO" /></a></p>209+<p>[<img alt="Markup.IO" src="images/apps/markupio.png)](http://markup.io" /></p>210 211 <p><a href="http://scrabb.ly">Scrabb.ly</a> is a massively multiplayer scrabble game initially created for the <a href="http://nodeknockout.com/">Node Knockout</a> competition.</p>212 221-<p><a href="http://scrabb.ly"><img src="images/apps/scrabbly.png" alt="Online Realtime Scrabble" /></a></p>213+<p>[<img alt="Online Realtime Scrabble" src="images/apps/scrabbly.png)](http://scrabb.ly" /></p>214 215 <p><a href="http://clickdummy.net/">ClickDummy</a> is a rapid mockup prototyping application for designers and dummies.</p>216 225-<p><a href="http://clickdummy.net"><img src="images/apps/clickdummy.png" alt="Mockup Prototying" /></a></p>217+<p>[<img alt="Mockup Prototying" src="images/apps/clickdummy.png)](http://clickdummy.net" /></p>218 219 <p><a href="http://nodeknockout.com">Node Knockout</a> organized the first ever node-specific competition with hundreds of contestants.</p>220 229-<p><a href="http://nodeknockout.com"><img src="images/apps/nodeko.png" alt="Node Knockout Competition Express" /></a></p>221+<p>[<img alt="Node Knockout Competition Express" src="images/apps/nodeko.png)](http://nodeknockout.com" /></p>222 223 <p><a href="http://widescript.com">Widescript</a> is an innovative app that helps you focus and interact with your texts - on your desktop, your couch or on the go.</p>224 233-<p><a href="http://widescript.com"><img src="images/apps/widescript.png" alt="Widescript" /></a></p>225+<p>[<img alt="Widescript" src="images/apps/widescript.png)](http://widescript.com" /></p>226 227 <p><a href="http://www.e-resistible.co.uk/">e-resistable</a> is an online order takeaway system providing an intuitive way to fill your belly from your computer!</p>228 237-<p><a href="http://www.e-resistible.co.uk"><img src="images/apps/e-resistable.png" alt="Online Takeaway" /></a></p>229+<p>[<img alt="Online Takeaway" src="images/apps/e-resistable.png)](http://www.e-resistible.co.uk" /></p>230 231 <p><a href="http://toptwittertrends.com">Top Twitter Trends</a> utilizes MongoDB, Socket.IO, jQuery and many other exciting libraries to bring you trending tweets in realtime.</p>232 241-<p><a href="http://toptwittertrends.com"><img src="images/apps/toptwittertrends.png" alt="Twitter Trends" /></a></p>233+<p>[<img alt="Twitter Trends" src="images/apps/toptwittertrends.png)](http://toptwittertrends.com" /></p>234 243-<br />235+<p><br /></p>236 245-237 <p>The applications shown above are not listed in any specific order. To have an application added or removed please contact <a href="http://github.com/visionmedia">TJ Holowaychuk</a>.</p>247-248-</div>238 </div>239 </div>240 </body>241 </html>deleted:docs/contrib.1-82 removed
1-.\" generated with Ronn/v0.7.32-.\" http://github.com/rtomayko/ronn/tree/0.7.33-.4-.TH "CONTRIB" "" "March 2011" "" ""5-.6-.SH "NAME"7-\fBcontrib\fR8-.9-.SS "Development Dependencies"10-Express development dependencies are stored within the \fI\./support\fR directory\. To update them execute:11-.12-.IP "" 413-.14-.nf15-16-$ git submodule update \-\-init17-.18-.fi19-.20-.IP "" 021-.22-.SS "Running Tests"23-Express uses the Expresso \fIhttp://github\.com/visionmedia/expresso\fR TDD framework to write and run elegant test suites extremely fast\. To run all test suites simply execute:24-.25-.IP "" 426-.27-.nf28-29-$ make test30-.31-.fi32-.33-.IP "" 034-.35-.P36-To target specific suites we may specify the files via:37-.38-.IP "" 439-.40-.nf41-42-$ make test TESTS=test/view\.test\.js43-.44-.fi45-.46-.IP "" 047-.48-.P49-To check test coverage run:50-.51-.IP "" 452-.53-.nf54-55-$ make test\-cov56-.57-.fi58-.59-.IP "" 060-.61-.SS "Contributions"62-To accept a contribution, you should follow these guidelines:63-.64-.IP "\(bu" 465-All tests \fImust\fR pass66-.67-.IP "\(bu" 468-Your alterations or additions \fImust\fR include tests69-.70-.IP "\(bu" 471-Your commit(s) should be \fIfocused\fR, do not commit once for several changes72-.73-.IP "\(bu" 474-Do \fInot\fR alter release information such as the \fIversion\fR, or \fIHistory\.md\fR75-.76-.IP "\(bu" 477-Indents are \fI2\fR spaces\.78-.79-.IP "" 080-.81-.SS "Documentation"82-To contribute documentation edit the markdown files in \fI\./docs\fR, however do \fInot\fR run \fImake docs\fR, as they will be re\-built and published with each release\.modified:docs/contrib.html+5 added-23 removed
188 unmodified lines189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193-<div class='mp'>194-<h2 id="Express">Express</h2>195-<p class="man-name">196- <code>contrib</code>197-</p>193 <h3 id="Development-Dependencies">Development Dependencies</h3>194 195 <p>Express development dependencies are stored within the <em>./support</em> directory. To196 update them execute:</p>197 203-<pre><code>$ git submodule update --init204-</code></pre>198+<pre><code>$ git submodule update --init</code></pre>199 200 <h3 id="Running-Tests">Running Tests</h3>201 202 <p>Express uses the <a href="http://github.com/visionmedia/expresso">Expresso</a> TDD203 framework to write and run elegant test suites extremely fast. To run all test suites204 simply execute:</p>205 212-<pre><code>$ make test213-</code></pre>206+<pre><code>$ make test</code></pre>207 208 <p>To target specific suites we may specify the files via:</p>209 217-<pre><code>$ make test TESTS=test/view.test.js218-</code></pre>210+<pre><code>$ make test TESTS=test/view.test.js</code></pre>211 212 <p>To check test coverage run:</p>213 222-<pre><code>$ make test-cov223-</code></pre>214+<pre><code>$ make test-cov</code></pre>215 216 <h3 id="Contributions">Contributions</h3>217 218 <p>To accept a contribution, you should follow these guidelines:</p>219 229-<ul>230-<li>All tests <em>must</em> pass</li>231-<li>Your alterations or additions <em>must</em> include tests</li>232-<li>Your commit(s) should be <em>focused</em>, do not commit once for several changes</li>233-<li>Do <em>not</em> alter release information such as the <em>version</em>, or <em>History.md</em></li>234-<li>Indents are <em>2</em> spaces.</li>235-</ul>220+<ul><li>All tests <em>must</em> pass</li><li>Your alterations or additions <em>must</em> include tests</li><li>Your commit(s) should be <em>focused</em>, do not commit once for several changes</li><li>Do <em>not</em> alter release information such as the <em>version</em>, or <em>History.md</em></li><li>Indents are <em>2</em> spaces.</li></ul>221 237-222 <h3 id="Documentation">Documentation</h3>223 224 <p>To contribute documentation edit the markdown files in <em>./docs</em>, however225 do <em>not</em> run <em>make docs</em>, as they will be re-built and published with each release.</p>242-243-</div>226 </div>227 </div>228 </body>229 </html>deleted:docs/executable.1-31 removed
1-.\" generated with Ronn/v0.7.32-.\" http://github.com/rtomayko/ronn/tree/0.7.33-.4-.TH "EXECUTABLE" "" "March 2011" "" ""5-.6-.SH "NAME"7-\fBexecutable\fR8-.9-.SH "Synopsis"10-.11-.nf12-13-express [options] [PATH]14-.15-.fi16-.17-.SH "Description"18-The \fIexpress\fR executable generates apps at the given \fBPATH\fR or the current working directory\. Although Express is not bound to a specific application structure, this executable creates a maintainable base app\.19-.20-.SH "Options"21-.22-.nf23-24- \-s, \-\-sessions Add session support25- \-t, \-\-template ENGINE Add template ENGINE support (jade|ejs)\. Defaults to jade26- \-c, \-\-css ENGINE Add stylesheet ENGINE support (less|sass|stylus)\. Defaults to plain css27- \-v, \-\-version Output framework version28- \-h, \-\-help Output help information29-.30-.fi31-modified:docs/executable.html+3 added-12 removed
188 unmodified lines189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193-<div class='mp'>194-<h2 id="Express">Express</h2>195-<p class="man-name">196- <code>executable</code>197-</p>193 <h2 id="Synopsis">Synopsis</h2>194 200-<pre><code>express [options] [PATH]201-</code></pre>195+<pre><code>express [options] [PATH]</code></pre>196 197 <h2 id="Description">Description</h2>198 205-<p>The <em>express</em> executable generates apps at the given <strong>PATH</strong> or the199+<p>The <em>express</em> executable generates apps at the given <strong>PATH</strong> or the 200 current working directory. Although Express is not bound to a specific201 application structure, this executable creates a maintainable base app.</p>202 203 <h2 id="Options">Options</h2>1 unmodified line205 <pre><code> -s, --sessions Add session support206 -t, --template ENGINE Add template ENGINE support (jade|ejs). Defaults to jade207 -c, --css ENGINE Add stylesheet ENGINE support (less|sass|stylus). Defaults to plain css208 -v, --version Output framework version215- -h, --help Output help information216-</code></pre>217-218-</div>209+ -h, --help Output help information</code></pre>210 </div>211 </div>212 </body>213 </html>deleted:docs/guide.1-2099 removed
1-.\" generated with Ronn/v0.7.32-.\" http://github.com/rtomayko/ronn/tree/0.7.33-.4-.TH "GUIDE" "" "March 2011" "" ""5-.6-.SH "NAME"7-\fBguide\fR8-.9-.SS "Installation"10-.11-.nf12-13-$ npm install express14-.15-.fi16-.17-.SS "Creating A Server"18-To create an instance of the \fIexpress\.HTTPServer\fR, simply invoke the \fIcreateServer()\fR method\. With our instance \fIapp\fR we can then define routes based on the HTTP verbs, in this example \fIapp\.get()\fR\.19-.20-.IP "" 421-.22-.nf23-24-var app = require(\'express\')\.createServer();25-26-app\.get(\'/\', function(req, res){27- res\.send(\'hello world\');28-});29-30-app\.listen(3000);31-.32-.fi33-.34-.IP "" 035-.36-.SS "Creating An HTTPS Server"37-To initialize a \fIexpress\.HTTPSServer\fR we do the same as above, however we pass an options object, accepting \fIkey\fR, \fIcert\fR and the others mentioned in node\'s https documentation \fIhttp://nodejs\.org/docs/v0\.3\.7/api/https\.html#https\.createServer\fR\.38-.39-.IP "" 440-.41-.nf42-43- var app = require(\'express\')\.createServer({ key: \.\.\. });44-.45-.fi46-.47-.IP "" 048-.49-.SS "Configuration"50-Express supports arbitrary environments, such as \fIproduction\fR and \fIdevelopment\fR\. Developers can use the \fIconfigure()\fR method to setup needs required by the current environment\. When \fIconfigure()\fR is called without an environment name it will be run in \fIevery\fR environment prior to the environment specific callback\.51-.52-.P53-In the example below we only \fIdumpExceptions\fR, and respond with exception stack traces in \fIdevelopment\fR mode, however for both environments we utilize \fImethodOverride\fR and \fIbodyParser\fR\. Note the use of \fIapp\.router\fR, which can (optionally) be used to mount the application routes, otherwise the first call to \fIapp\.get()\fR, \fIapp\.post()\fR, etc will mount the routes\.54-.55-.IP "" 456-.57-.nf58-59-app\.configure(function(){60- app\.use(express\.methodOverride());61- app\.use(express\.bodyParser());62- app\.use(app\.router);63-});64-65-app\.configure(\'development\', function(){66- app\.use(express\.static(__dirname + \'/public\'));67- app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));68-});69-70-app\.configure(\'production\', function(){71- var oneYear = 31557600000;72- app\.use(express\.static({ root: __dirname + \'/public\', maxAge: oneYear }));73- app\.use(express\.errorHandler());74-});75-.76-.fi77-.78-.IP "" 079-.80-.P81-For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:82-.83-.IP "" 484-.85-.nf86-87- app\.configure(function(){88- app\.set(\'views\', __dirname + \'/views\');89- app\.set(\'views\');90- // => "/absolute/path/to/views"91-92- app\.enable(\'some feature\');93- // same as app\.set(\'some feature\', true);94-95- app\.disable(\'some feature\');96- // same as app\.set(\'some feature\', false);97-98- app\.enabled(\'some feature\')99- // => false100- });101-.102-.fi103-.104-.IP "" 0105-.106-.P107-To alter the environment we can set the \fINODE_ENV\fR environment variable, for example:108-.109-.IP "" 4110-.111-.nf112-113-$ NODE_ENV=production node app\.js114-.115-.fi116-.117-.IP "" 0118-.119-.P120-This is \fIvery\fR important, as many caching mechanisms are \fIonly enabled\fR when in production\.121-.122-.SS "Settings"123-Express supports the following settings out of the box:124-.125-.IP "\(bu" 4126-\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.127-.128-.IP "\(bu" 4129-\fIviews\fR Root views directory defaulting to \fBCWD/views\fR130-.131-.IP "\(bu" 4132-\fIview engine\fR Default view engine name for views rendered without extensions133-.134-.IP "\(bu" 4135-\fIview options\fR An object specifying global view options136-.137-.IP "" 0138-.139-.SS "Routing"140-Express utilizes the HTTP verbs to provide a meaningful, expressive routing API\. For example we may want to render a user\'s account for the path \fI/user/12\fR, this can be done by defining the route below\. The values associated to the named placeholders are available as \fBreq\.params\fR\.141-.142-.IP "" 4143-.144-.nf145-146-app\.get(\'/user/:id\', function(req, res){147- res\.send(\'user \' + req\.params\.id);148-});149-.150-.fi151-.152-.IP "" 0153-.154-.P155-A route is simple a string which is compiled to a \fIRegExp\fR internally\. For example when \fI/user/:id\fR is compiled, a simplified version of the regexp may look similar to:156-.157-.IP "" 4158-.159-.nf160-161-\e/user\e/([^\e/]+)\e/?162-.163-.fi164-.165-.IP "" 0166-.167-.P168-Regular expression literals may also be passed for complex uses\. Since capture groups with literal \fIRegExp\fR\'s are anonymous we can access them directly \fBreq\.params\fR\. So our first capture group would be \fIreq\.params[0]\fR and the second would follow as \fIreq\.params[1]\fR\.169-.170-.IP "" 4171-.172-.nf173-174-app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){175- res\.send(req\.params);176-});177-.178-.fi179-.180-.IP "" 0181-.182-.P183-Curl requests against the previously defined route:184-.185-.IP "" 4186-.187-.nf188-189- $ curl http://dev:3000/user190- [null,null]191- $ curl http://dev:3000/users192- [null,null]193- $ curl http://dev:3000/users/1194- ["1",null]195- $ curl http://dev:3000/users/1\.\.15196- ["1","15"]197-.198-.fi199-.200-.IP "" 0201-.202-.P203-Below are some route examples, and the associated paths that they may consume:204-.205-.IP "" 4206-.207-.nf208-209- "/user/:id"210- /user/12211-212- "/users/:id?"213- /users/5214- /users215-216- "/files/*"217- /files/jquery\.js218- /files/javascripts/jquery\.js219-220- "/file/*\.*"221- /files/jquery\.js222- /files/javascripts/jquery\.js223-224- "/user/:id/:operation?"225- /user/1226- /user/1/edit227-228- "/products\.:format"229- /products\.json230- /products\.xml231-232- "/products\.:format?"233- /products\.json234- /products\.xml235- /products236-237- "/user/:id\.:format?"238- /user/12239- /user/12\.json240-.241-.fi242-.243-.IP "" 0244-.245-.P246-For example we can \fBPOST\fR some json, and echo the json back using the \fIbodyParser\fR middleware which will parse json request bodies (as well as others), and place the result in \fIreq\.body\fR:247-.248-.IP "" 4249-.250-.nf251-252-var express = require(\'express\')253- , app = express\.createServer();254-255-app\.use(express\.bodyParser());256-257-app\.post(\'/\', function(req, res){258- res\.send(req\.body);259-});260-261-app\.listen(3000);262-.263-.fi264-.265-.IP "" 0266-.267-.P268-Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use \fI\'/user/:id(\ed+)\'\fR which will \fInot\fR match unless the placeholder value contains only digits\.269-.270-.SS "Passing Route Control"271-We may pass control to the next \fImatching\fR route, by calling the \fIthird\fR argument, the \fInext()\fR function\. When a match cannot be made, control is passed back to Connect, and middleware continue to be invoked in the order that they are added via \fIuse()\fR\. The same is true for several routes which have the same path defined, they will simply be executed in order until one does \fInot\fR call \fInext()\fR and decides to respond\.272-.273-.IP "" 4274-.275-.nf276-277-app\.get(\'/users/:id?\', function(req, res, next){278- var id = req\.params\.id;279- if (id) {280- // do something281- } else {282- next();283- }284-});285-286-app\.get(\'/users\', function(req, res){287- // do something else288-});289-.290-.fi291-.292-.IP "" 0293-.294-.P295-The \fIapp\.all()\fR method is useful for applying the same logic for all HTTP verbs in a single call\. Below we use this to load a user from our fake database, and assign it to \fIreq\.user\fR\.296-.297-.IP "" 4298-.299-.nf300-301-var express = require(\'express\')302- , app = express\.createServer();303-304-var users = [{ name: \'tj\' }];305-306-app\.all(\'/user/:id/:op?\', function(req, res, next){307- req\.user = users[req\.params\.id];308- if (req\.user) {309- next();310- } else {311- next(new Error(\'cannot find user \' + req\.params\.id));312- }313-});314-315-app\.get(\'/user/:id\', function(req, res){316- res\.send(\'viewing \' + req\.user\.name);317-});318-319-app\.get(\'/user/:id/edit\', function(req, res){320- res\.send(\'editing \' + req\.user\.name);321-});322-323-app\.put(\'/user/:id\', function(req, res){324- res\.send(\'updating \' + req\.user\.name);325-});326-327-app\.get(\'*\', function(req, res){328- res\.send(\'what???\', 404);329-});330-331-app\.listen(3000);332-.333-.fi334-.335-.IP "" 0336-.337-.SS "Middleware"338-Middleware via Connect \fIhttp://github\.com/senchalabs/connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:339-.340-.IP "" 4341-.342-.nf343-344- var express = require(\'express\');345-346-var app = express\.createServer(347- express\.logger()348- , express\.bodyParser()349- );350-.351-.fi352-.353-.IP "" 0354-.355-.P356-Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks, in a progressive manor\.357-.358-.IP "" 4359-.360-.nf361-362-app\.use(express\.logger({ format: \':method :uri\' }));363-.364-.fi365-.366-.IP "" 0367-.368-.P369-Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:370-.371-.IP "" 4372-.373-.nf374-375-var connect = require(\'connect\');376-app\.use(connect\.logger());377-app\.use(connect\.bodyParser());378-.379-.fi380-.381-.IP "" 0382-.383-.P384-This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:385-.386-.IP "" 4387-.388-.nf389-390-app\.use(express\.logger());391-app\.use(express\.bodyParser());392-.393-.fi394-.395-.IP "" 0396-.397-.SS "Route Middleware"398-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\.399-.400-.P401-Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.402-.403-.IP "" 4404-.405-.nf406-407-app\.get(\'/user/:id\', function(req, res, next){408- loadUser(req\.params\.id, function(err, user){409- if (err) return next(err);410- res\.send(\'Viewing user \' + user\.name);411- });412-});413-.414-.fi415-.416-.IP "" 0417-.418-.P419-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\.420-.421-.IP "" 4422-.423-.nf424-425-function loadUser(req, res, next) {426- // You would fetch your user from the db427- var user = users[req\.params\.id];428- if (user) {429- req\.user = user;430- next();431- } else {432- next(new Error(\'Failed to load user \' + req\.params\.id));433- }434-}435-436-app\.get(\'/user/:id\', loadUser, function(req, res){437- res\.send(\'Viewing user \' + req\.user\.name);438-});439-.440-.fi441-.442-.IP "" 0443-.444-.P445-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\.446-.447-.IP "" 4448-.449-.nf450-451-function andRestrictToSelf(req, res, next) {452- req\.authenticatedUser\.id == req\.user\.id453- ? next()454- : next(new Error(\'Unauthorized\'));455-}456-457-app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){458- res\.send(\'Editing user \' + req\.user\.name);459-});460-.461-.fi462-.463-.IP "" 0464-.465-.P466-Keeping in mind that middleware are simply functions, we can define function that \fIreturns\fR the middleware in order to create a more expressive and flexible solution as shown below\.467-.468-.IP "" 4469-.470-.nf471-472-function andRestrictTo(role) {473- return function(req, res, next) {474- req\.authenticatedUser\.role == role475- ? next()476- : next(new Error(\'Unauthorized\'));477- }478-}479-480-app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){481- res\.send(\'Deleted user \' + req\.user\.name);482-});483-.484-.fi485-.486-.IP "" 0487-.488-.P489-Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.490-.491-.IP "" 4492-.493-.nf494-495-var a = [middleware1, middleware2]496- , b = [middleware3, middleware4]497- , all = [a, b];498-499-app\.get(\'/foo\', a, function(){});500-app\.get(\'/bar\', a, function(){});501-502-app\.get(\'/\', a, middleware3, middleware4, function(){});503-app\.get(\'/\', a, b, function(){});504-app\.get(\'/\', all, function(){});505-.506-.fi507-.508-.IP "" 0509-.510-.P511-For this example in full, view the route middleware example \fIhttp://github\.com/visionmedia/express/blob/master/examples/route\-middleware/app\.js\fR in the repository\.512-.513-.SS "HTTP Methods"514-We have seen \fIapp\.get()\fR a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as \fIapp\.post()\fR, \fIapp\.del()\fR, etc\.515-.516-.P517-A common example for \fIPOST\fR 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\.518-.519-.IP "" 4520-.521-.nf522-523- <form method="post" action="/">524- <input type="text" name="user[name]" />525- <input type="text" name="user[email]" />526- <input type="submit" value="Submit" />527- </form>528-.529-.fi530-.531-.IP "" 0532-.533-.P534-By default Express does not know what to do with this request body, so we should add the \fIbodyParser\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR and \fIapplication/json\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:535-.536-.IP "" 4537-.538-.nf539-540-app\.use(express\.bodyParser());541-.542-.fi543-.544-.IP "" 0545-.546-.P547-Our route below will now have access to the \fIreq\.body\.user\fR object which will contain the \fIname\fR and \fIemail\fR properties when defined\.548-.549-.IP "" 4550-.551-.nf552-553-app\.post(\'/\', function(req, res){554- console\.log(req\.body\.user);555- res\.redirect(\'back\');556-});557-.558-.fi559-.560-.IP "" 0561-.562-.P563-When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyParser\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.564-.565-.IP "" 4566-.567-.nf568-569-app\.use(express\.bodyParser());570-app\.use(express\.methodOverride());571-.572-.fi573-.574-.IP "" 0575-.576-.P577-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 \fIPUT\fR and \fIDELETE\fR can still be accessed by clients which can use them directly, although \fImethodOverride\fR provides a great solution for forms\. Below shows what the usage of \fIPUT\fR might look like:578-.579-.IP "" 4580-.581-.nf582-583-<form method="post" action="/">584- <input type="hidden" name="_method" value="put" />585- <input type="text" name="user[name]" />586- <input type="text" name="user[email]" />587- <input type="submit" value="Submit" />588-</form>589-590-app\.put(\'/\', function(){591- console\.log(req\.body\.user);592- res\.redirect(\'back\');593-});594-.595-.fi596-.597-.IP "" 0598-.599-.SS "Error Handling"600-Express provides the \fIapp\.error()\fR method which receives exceptions thrown within a route, or passed to \fInext(err)\fR\. Below is an example which serves different pages based on our ad\-hoc \fINotFound\fR exception:601-.602-.IP "" 4603-.604-.nf605-606-function NotFound(msg){607- this\.name = \'NotFound\';608- Error\.call(this, msg);609- Error\.captureStackTrace(this, arguments\.callee);610-}611-612-NotFound\.protoype\.__proto__ = Error\.prototype;613-614-app\.get(\'/404\', function(req, res){615- throw new NotFound;616-});617-618-app\.get(\'/500\', function(req, res){619- throw new Error(\'keyboard cat!\');620-});621-.622-.fi623-.624-.IP "" 0625-.626-.P627-We can call \fIapp\.error()\fR several times as shown below\. Here we check for an instanceof \fINotFound\fR and show the 404 page, or we pass on to the next error handler\.628-.629-.P630-Note that these handlers can be defined anywhere, as they will be placed below the route handlers on \fIlisten()\fR\. This allows for definition within \fIconfigure()\fR blocks so we can handle exceptions in different ways based on the environment\.631-.632-.IP "" 4633-.634-.nf635-636-app\.error(function(err, req, res, next){637- if (err instanceof NotFound) {638- res\.render(\'404\.jade\');639- } else {640- next(err);641- }642-});643-.644-.fi645-.646-.IP "" 0647-.648-.P649-Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like\. For example when node performs filesystem syscalls, you may receive an error object with the \fIerror\.code\fR of \fIENOENT\fR, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired\.650-.651-.IP "" 4652-.653-.nf654-655-app\.error(function(err, req, res){656- res\.render(\'500\.jade\', {657- error: err658- });659-});660-.661-.fi662-.663-.IP "" 0664-.665-.P666-Our apps could also utilize the Connect \fIerrorHandler\fR middleware to report on exceptions\. For example if we wish to output exceptions in "development" mode to \fIstderr\fR we can use:667-.668-.IP "" 4669-.670-.nf671-672-app\.use(express\.errorHandler({ dumpExceptions: true }));673-.674-.fi675-.676-.IP "" 0677-.678-.P679-Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:680-.681-.IP "" 4682-.683-.nf684-685-app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));686-.687-.fi688-.689-.IP "" 0690-.691-.P692-The \fIerrorHandler\fR middleware also responds with \fIjson\fR if \fIAccept: application/json\fR is present, which is useful for developing apps that rely heavily on client\-side JavaScript\.693-.694-.SS "Route Param Pre\-conditions"695-Route param 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 \fI/user/:id\fR, we might typically do something like below:696-.697-.IP "" 4698-.699-.nf700-701-app\.get(\'/user/:userId\', function(req, res, next){702- User\.get(req\.params\.userId, function(err, user){703- if (err) return next(err);704- res\.send(\'user \' + user\.name);705- });706-});707-.708-.fi709-.710-.IP "" 0711-.712-.P713-With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database\. Below we invoke \fIapp\.param()\fR with the parameter name we wish to map to some middleware, as you can see we receive the \fIid\fR argument which contains the placeholder value\. Using this we load the user and perform error handling as usual, and simple call \fInext()\fR to pass control to the next precondition or route handler\.714-.715-.IP "" 4716-.717-.nf718-719-app\.param(\'userId\', function(req, res, next, id){720- User\.get(id, function(err, user){721- if (err) return next(err);722- if (!user) return next(new Error(\'failed to find user\'));723- req\.user = user;724- next();725- });726-});727-.728-.fi729-.730-.IP "" 0731-.732-.P733-Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:734-.735-.IP "" 4736-.737-.nf738-739-app\.get(\'/user/:userId\', function(req, res){740- res\.send(\'user \' + req\.user\.name);741-});742-.743-.fi744-.745-.IP "" 0746-.747-.P748-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 \fInext(err)\fR\.749-.750-.IP "" 4751-.752-.nf753-754-app\.param(\'number\', function(n){ return parseInt(n, 10); });755-.756-.fi757-.758-.IP "" 0759-.760-.P761-We may also apply the same callback to several placeholders, for example a route GET \fI/commits/:from\-:to\fR are both numbers, so we may define them as an array:762-.763-.IP "" 4764-.765-.nf766-767-app\.param([\'from\', \'to\'], function(n){ return parseInt(n, 10); });768-.769-.fi770-.771-.IP "" 0772-.773-.SS "View Rendering"774-View filenames take the form "<name>\.<engine>", where <engine> is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.compile(str, options)\fR, and return a \fIFunction\fR to comply with Express\. To alter this behaviour \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by ejs\.775-.776-.P777-Below is an example using Jade \fIhttp://github\.com/visionmedia/jade\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.jade\fR will be passed as the \fIbody\fR local variable in \fIlayout\.jade\fR\.778-.779-.IP "" 4780-.781-.nf782-783-app\.get(\'/\', function(req, res){784- res\.render(\'index\.jade\', { title: \'My Site\' });785-});786-.787-.fi788-.789-.IP "" 0790-.791-.P792-The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using jade we could set:793-.794-.IP "" 4795-.796-.nf797-798-app\.set(\'view engine\', \'jade\');799-.800-.fi801-.802-.IP "" 0803-.804-.P805-Allowing us to render with:806-.807-.IP "" 4808-.809-.nf810-811-res\.render(\'index\');812-.813-.fi814-.815-.IP "" 0816-.817-.P818-vs:819-.820-.IP "" 4821-.822-.nf823-824-res\.render(\'index\.jade\');825-.826-.fi827-.828-.IP "" 0829-.830-.P831-When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:832-.833-.IP "" 4834-.835-.nf836-837-res\.render(\'another\-page\.ejs\');838-.839-.fi840-.841-.IP "" 0842-.843-.P844-Express also provides the \fIview options\fR setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:845-.846-.IP "" 4847-.848-.nf849-850-app\.set(\'view options\', {851- layout: false852-});853-.854-.fi855-.856-.IP "" 0857-.858-.P859-Which can then be overridden within the \fIres\.render()\fR call if need be:860-.861-.IP "" 4862-.863-.nf864-865-res\.render(\'myview\.ejs\', { layout: true });866-.867-.fi868-.869-.IP "" 0870-.871-.P872-When an alternate layout is required, we may also specify a path\. For example if we have \fIview engine\fR set to \fIjade\fR and a file named \fI\./views/mylayout\.jade\fR we can simply pass:873-.874-.IP "" 4875-.876-.nf877-878-res\.render(\'page\', { layout: \'mylayout\' });879-.880-.fi881-.882-.IP "" 0883-.884-.P885-Otherwise we must specify the extension:886-.887-.IP "" 4888-.889-.nf890-891-res\.render(\'page\', { layout: \'mylayout\.jade\' });892-.893-.fi894-.895-.IP "" 0896-.897-.P898-These paths may also be absolute:899-.900-.IP "" 4901-.902-.nf903-904-res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });905-.906-.fi907-.908-.IP "" 0909-.910-.P911-A good example of this is specifying custom \fIejs\fR opening and closing tags:912-.913-.IP "" 4914-.915-.nf916-917-app\.set(\'view options\', {918- open: \'{{\',919- close: \'}}\'920-});921-.922-.fi923-.924-.IP "" 0925-.926-.SS "View Partials"927-The Express view system has built\-in support for partials and collections, which are "mini" views representing a document fragment\. For example rather than iterating in a view to display comments, we would use a partial with collection support:928-.929-.IP "" 4930-.931-.nf932-933-partial(\'comment\', { collection: comments });934-.935-.fi936-.937-.IP "" 0938-.939-.P940-If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:941-.942-.IP "" 4943-.944-.nf945-946-partial(\'comment\', comments);947-.948-.fi949-.950-.IP "" 0951-.952-.P953-When using the partial collection support a few "magic" variables are provided for free:954-.955-.IP "\(bu" 4956-\fIfirstInCollection\fR true if this is the first object957-.958-.IP "\(bu" 4959-\fIindexInCollection\fR index of the object in the collection960-.961-.IP "\(bu" 4962-\fIlastInCollection\fR true if this is the last object963-.964-.IP "\(bu" 4965-\fIcollectionLength\fR length of the collection966-.967-.IP "" 0968-.969-.P970-Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well\. So for example if we were to render a blog post with \fIpartial(\'blog/post\', post)\fR it would generate the \fIpost\fR local, but the view calling this function had the local \fIuser\fR, it would be available to the \fIblog/post\fR view as well\.971-.972-.P973-For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.974-.975-.P976-\fBNOTE:\fR be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views\. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead\.977-.978-.SS "View Lookup"979-View lookup is performed relative to the parent view, for example if we had a page view named \fIviews/user/list\.jade\fR, and within that view we did \fIpartial(\'edit\')\fR it would attempt to load \fIviews/user/edit\.jade\fR, whereas \fIpartial(\'\.\./messages\')\fR would load \fIviews/messages\.jade\fR\.980-.981-.P982-The view system also allows for index templates, allowing you to have a directory of the same name\. For example within a route we may have \fIres\.render(\'users\')\fR either \fIviews/users\.jade\fR, or \fIviews/users/index\.jade\fR\.983-.984-.P985-When utilizing index views as shown above, we may reference \fIviews/users/index\.jade\fR from a view in the same directory by \fIpartial(\'users\')\fR, and the view system will try \fI\.\./users/index\fR, preventing us from needing to call \fIpartial(\'index\')\fR\.986-.987-.SS "Template Engines"988-Below are a few template engines commonly used with Express:989-.990-.IP "\(bu" 4991-Jade \fIhttp://jade\-lang\.com\fR haml\.js successor992-.993-.IP "\(bu" 4994-EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript995-.996-.IP "\(bu" 4997-CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating998-.999-.IP "\(bu" 41000-jQuery Templates \fIhttps://github\.com/kof/node\-jqtpl\fR for node1001-.1002-.IP "" 01003-.1004-.SS "Session Support"1005-Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieParser\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.1006-.1007-.IP "" 41008-.1009-.nf1010-1011-app\.use(express\.cookieParser());1012-app\.use(express\.session({ secret: "keyboard cat" }));1013-.1014-.fi1015-.1016-.IP "" 01017-.1018-.P1019-By default the \fIsession\fR middleware uses the memory store bundled with Connect, however many implementations exist\. For example connect\-redis \fIhttp://github\.com/visionmedia/connect\-redis\fR supplies a Redis \fIhttp://code\.google\.com/p/redis/\fR session store and can be used as shown below:1020-.1021-.IP "" 41022-.1023-.nf1024-1025-var RedisStore = require(\'connect\-redis\');1026-app\.use(express\.cookieParser());1027-app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));1028-.1029-.fi1030-.1031-.IP "" 01032-.1033-.P1034-Now the \fIreq\.session\fR and \fIreq\.sessionStore\fR properties will be accessible to all routes and subsequent middleware\. Properties on \fIreq\.session\fR are automatically saved on a response, so for example if we wish to shopping cart data:1035-.1036-.IP "" 41037-.1038-.nf1039-1040-var RedisStore = require(\'connect\-redis\');1041-app\.use(express\.bodyParser());1042-app\.use(express\.cookieParser());1043-app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));1044-1045-app\.post(\'/add\-to\-cart\', function(req, res){1046- // Perhaps we posted several items with a form1047- // (use the bodyParser() middleware for this)1048- var items = req\.body\.items;1049- req\.session\.items = items;1050- res\.redirect(\'back\');1051-});1052-1053-app\.get(\'/add\-to\-cart\', function(req, res){1054- // When redirected back to GET /add\-to\-cart1055- // we could check req\.session\.items && req\.session\.items\.length1056- // to print out a message1057- if (req\.session\.items && req\.session\.items\.length) {1058- req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);1059- }1060- res\.render(\'shopping\-cart\');1061-});1062-.1063-.fi1064-.1065-.IP "" 01066-.1067-.P1068-The \fIreq\.session\fR object also has methods such as \fISession#touch()\fR, \fISession#destroy()\fR, \fISession#regenerate()\fR among others to maintain and manipulate sessions\. For more information view the Connect Session \fIhttp://senchalabs\.github\.com/connect/middleware\-session\.html\fR documentation\.1069-.1070-.SS "Migration Guide"1071-Express 1\.x developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application to work with Express 2\.x, Connect 1\.x, and Node 0\.4\.x\.1072-.1073-.SS "req\.header(key[, defaultValue])"1074-Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1075-.1076-.IP "" 41077-.1078-.nf1079-1080-req\.header(\'Host\');1081-req\.header(\'host\');1082-req\.header(\'Accept\', \'*/*\');1083-.1084-.fi1085-.1086-.IP "" 01087-.1088-.P1089-The \fIReferrer\fR and \fIReferer\fR header fields are special\-cased, either will work:1090-.1091-.IP "" 41092-.1093-.nf1094-1095-// sent Referrer: http://google\.com1096-1097-req\.header(\'Referer\');1098-// => "http://google\.com"1099-1100-req\.header(\'Referrer\');1101-// => "http://google\.com"1102-.1103-.fi1104-.1105-.IP "" 01106-.1107-.SS "req\.accepts(type)"1108-Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1109-.1110-.P1111-When the \fIAccept\fR header is not present \fItrue\fR is returned\. Otherwise the given \fItype\fR is matched by an exact match, and then subtypes\. You may pass the subtype such as "html" which is then converted internally to "text/html" using the mime lookup table\.1112-.1113-.IP "" 41114-.1115-.nf1116-1117-// Accept: text/html1118-req\.accepts(\'html\');1119-// => true1120-1121-// Accept: text/*; application/json1122-req\.accepts(\'html\');1123-req\.accepts(\'text/html\');1124-req\.accepts(\'text/plain\');1125-req\.accepts(\'application/json\');1126-// => true1127-1128-req\.accepts(\'image/png\');1129-req\.accepts(\'png\');1130-// => false1131-.1132-.fi1133-.1134-.IP "" 01135-.1136-.SS "req\.is(type)"1137-Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.1138-.1139-.IP "" 41140-.1141-.nf1142-1143- // With Content\-Type: text/html; charset=utf\-81144- req\.is(\'html\');1145- req\.is(\'text/html\');1146- // => true1147-1148- // When Content\-Type is application/json1149- req\.is(\'json\');1150- req\.is(\'application/json\');1151- // => true1152-1153- req\.is(\'html\');1154- // => false1155-.1156-.fi1157-.1158-.IP "" 01159-.1160-.P1161-Ad\-hoc callbacks can also be registered with Express, to perform assertions again the request, for example if we need an expressive way to check if our incoming request is an image, we can register \fI"an image"\fR callback:1162-.1163-.IP "" 41164-.1165-.nf1166-1167- app\.is(\'an image\', function(req){1168- return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1169- });1170-.1171-.fi1172-.1173-.IP "" 01174-.1175-.P1176-Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1177-.1178-.IP "" 41179-.1180-.nf1181-1182- app\.post(\'/image/upload\', function(req, res, next){1183- if (req\.is(\'an image\')) {1184- // do something1185- } else {1186- next();1187- }1188- });1189-.1190-.fi1191-.1192-.IP "" 01193-.1194-.P1195-Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1196-.1197-.P1198-Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1199-.1200-.IP "" 41201-.1202-.nf1203-1204-req\.is(\'image/*\');1205-.1206-.fi1207-.1208-.IP "" 01209-.1210-.P1211-We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1212-.1213-.IP "" 41214-.1215-.nf1216-1217-req\.is(\'*/json\');1218-.1219-.fi1220-.1221-.IP "" 01222-.1223-.SS "req\.param(name[, default])"1224-Return the value of param \fIname\fR when present or \fIdefault\fR\.1225-.1226-.IP "\(bu" 41227-Checks route params (\fIreq\.params\fR), ex: /user/:id1228-.1229-.IP "\(bu" 41230-Checks query string params (\fIreq\.query\fR), ex: ?id=121231-.1232-.IP "\(bu" 41233-Checks urlencoded body params (\fIreq\.body\fR), ex: id=121234-.1235-.IP "" 01236-.1237-.P1238-To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the _express\.bodyParser middleware\.1239-.1240-.SS "req\.flash(type[, msg])"1241-Queue flash \fImsg\fR of the given \fItype\fR\.1242-.1243-.IP "" 41244-.1245-.nf1246-1247-req\.flash(\'info\', \'email sent\');1248-req\.flash(\'error\', \'email delivery failed\');1249-req\.flash(\'info\', \'email re\-sent\');1250-// => 21251-1252-req\.flash(\'info\');1253-// => [\'email sent\', \'email re\-sent\']1254-1255-req\.flash(\'info\');1256-// => []1257-1258-req\.flash();1259-// => { error: [\'email delivery failed\'], info: [] }1260-.1261-.fi1262-.1263-.IP "" 01264-.1265-.P1266-Flash notification message may also utilize formatters, by default only the %s string formatter is available:1267-.1268-.IP "" 41269-.1270-.nf1271-1272-req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1273-.1274-.fi1275-.1276-.IP "" 01277-.1278-.SS "req\.isXMLHttpRequest"1279-Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1280-.1281-.IP "" 41282-.1283-.nf1284-1285-req\.xhr1286-req\.isXMLHttpRequest1287-.1288-.fi1289-.1290-.IP "" 01291-.1292-.SS "res\.header(key[, val])"1293-Get or set the response header \fIkey\fR\.1294-.1295-.IP "" 41296-.1297-.nf1298-1299-res\.header(\'Content\-Length\');1300-// => undefined1301-1302-res\.header(\'Content\-Length\', 123);1303-// => 1231304-1305-res\.header(\'Content\-Length\');1306-// => 1231307-.1308-.fi1309-.1310-.IP "" 01311-.1312-.SS "res\.contentType(type)"1313-Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1314-.1315-.IP "" 41316-.1317-.nf1318-1319- var filename = \'path/to/image\.png\';1320- res\.contentType(filename);1321- // Content\-Type is now "image/png"1322-.1323-.fi1324-.1325-.IP "" 01326-.1327-.SS "res\.attachment([filename])"1328-Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1329-.1330-.IP "" 41331-.1332-.nf1333-1334- res\.attachment(\'path/to/my/image\.png\');1335-.1336-.fi1337-.1338-.IP "" 01339-.1340-.SS "res\.sendfile(path[, options[, callback]])"1341-Used by \fBres\.download()\fR to transfer an arbitrary file\.1342-.1343-.IP "" 41344-.1345-.nf1346-1347-res\.sendfile(\'path/to/my\.file\');1348-.1349-.fi1350-.1351-.IP "" 01352-.1353-.P1354-This method accepts an optional callback which is called when an error occurs, or when the transfer is complete\. By default failures call \fBnext(err)\fR, however when a callback is supplied you must do this explicitly, or act on the error\.1355-.1356-.IP "" 41357-.1358-.nf1359-1360-res\.sendfile(path, function(err){1361- if (err) {1362- next(err);1363- } else {1364- console\.log(\'transferred %s\', path);1365- }1366-});1367-.1368-.fi1369-.1370-.IP "" 01371-.1372-.P1373-Options may also be passed to the internal \fIfs\.createReadStream()\fR call, for example altering the \fIbufferSize\fR:1374-.1375-.IP "" 41376-.1377-.nf1378-1379-res\.sendfile(path, { bufferSize: 1024 }, function(err){1380- // handle1381-});1382-.1383-.fi1384-.1385-.IP "" 01386-.1387-.SS "res\.download(file[, filename[, callback]])"1388-Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1389-.1390-.IP "" 41391-.1392-.nf1393-1394-res\.download(\'path/to/image\.png\');1395-res\.download(\'path/to/image\.png\', \'foo\.png\');1396-.1397-.fi1398-.1399-.IP "" 01400-.1401-.P1402-This is equivalent to:1403-.1404-.IP "" 41405-.1406-.nf1407-1408-res\.attachment(file);1409-res\.sendfile(file);1410-.1411-.fi1412-.1413-.IP "" 01414-.1415-.P1416-An optional callback may be supplied as either the second or third argument, which is passed to \fIres\.sendfile()\fR:1417-.1418-.IP "" 41419-.1420-.nf1421-1422-res\.download(path, \'expenses\.doc\', function(err){1423- // handle1424-});1425-.1426-.fi1427-.1428-.IP "" 01429-.1430-.SS "res\.send(body|status[, headers|status[, status]])"1431-The \fIres\.send()\fR method is a high level response utility allowing you to pass objects to respond with json, strings for html, Buffer instances, or numbers representing the status code\. The following are all valid uses:1432-.1433-.IP "" 41434-.1435-.nf1436-1437- res\.send(); // 2041438- res\.send(new Buffer(\'wahoo\'));1439- res\.send({ some: \'json\' });1440- res\.send(\'<p>some html</p>\');1441- res\.send(\'Sorry, cant find that\', 404);1442- res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1443- res\.send(404);1444-.1445-.fi1446-.1447-.IP "" 01448-.1449-.P1450-By default the \fIContent\-Type\fR response header is set, however if explicitly assigned through \fBres\.send()\fR or previously with \fBres\.header()\fR or \fBres\.contentType()\fR it will not be set again\.1451-.1452-.P1453-Note that this method \fIend()\fRs the response, so you will want to use node\'s \fIres\.write()\fR for multiple writes or streaming\.1454-.1455-.SS "res\.redirect(url[, status])"1456-Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1457-.1458-.IP "" 41459-.1460-.nf1461-1462-res\.redirect(\'/\', 301);1463-res\.redirect(\'/account\');1464-res\.redirect(\'http://google\.com\');1465-res\.redirect(\'home\');1466-res\.redirect(\'back\');1467-.1468-.fi1469-.1470-.IP "" 01471-.1472-.P1473-Express supports "redirect mapping", which by default provides \fIhome\fR, and \fIback\fR\. The \fIback\fR map checks the \fIReferrer\fR and \fIReferer\fR headers, while \fIhome\fR utilizes the "home" setting and defaults to "/"\.1474-.1475-.SS "res\.cookie(name, val[, options])"1476-Sets the given cookie \fIname\fR to \fIval\fR, with options \fIhttpOnly\fR, \fIsecure\fR, \fIexpires\fR etc\.1477-.1478-.IP "" 41479-.1480-.nf1481-1482-// "Remember me" for 15 minutes1483-res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1484-.1485-.fi1486-.1487-.IP "" 01488-.1489-.P1490-The \fImaxAge\fR property may be used to set \fIexpires\fR relative to \fIDate\.now()\fR in milliseconds, so our example above can now become:1491-.1492-.IP "" 41493-.1494-.nf1495-1496-res\.cookie(\'rememberme\', \'yes\', { maxAge: 900000 });1497-.1498-.fi1499-.1500-.IP "" 01501-.1502-.P1503-To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1504-.1505-.IP "" 41506-.1507-.nf1508-1509-app\.use(express\.cookieParser());1510-1511-app\.get(\'/\', function(req, res){1512- // use req\.cookies\.rememberme1513-});1514-.1515-.fi1516-.1517-.IP "" 01518-.1519-.SS "res\.clearCookie(name)"1520-Clear cookie \fIname\fR by setting "expires" far in the past\.1521-.1522-.IP "" 41523-.1524-.nf1525-1526-res\.clearCookie(\'rememberme\');1527-.1528-.fi1529-.1530-.IP "" 01531-.1532-.SS "res\.render(view[, options[, fn]])"1533-Render \fIview\fR with the given \fIoptions\fR and optional callback \fIfn\fR\. When a callback function is given a response will \fInot\fR be made automatically, however otherwise a response of \fI200\fR and \fItext/html\fR is given\.1534-.1535-.P1536-The \fIoptions\fR passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:1537-.1538-.IP "" 41539-.1540-.nf1541-1542-var user = { name: \'tj\' };1543-res\.render(\'index\', { layout: false, user: user });1544-.1545-.fi1546-.1547-.IP "" 01548-.1549-.SS "res\.partial(view[, options])"1550-Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1551-.1552-.IP "\(bu" 41553-\fIobject\fR the object named by \fIas\fR or derived from the view name1554-.1555-.IP "\(bu" 41556-\fIas\fR Variable name for each \fIcollection\fR or \fIobject\fR value, defaults to the view name\.1557-.1558-.IP "\(bu" 41559-as: \'something\' will add the \fIsomething\fR local variable1560-.1561-.IP "\(bu" 41562-as: this will use the collection value as the template context1563-.1564-.IP "\(bu" 41565-as: global will merge the collection value\'s properties with \fIlocals\fR1566-.1567-.IP "" 01568-1569-.1570-.IP "\(bu" 41571-\fIcollection\fR Array of objects, the name is derived from the view name itself\. For example \fIvideo\.html\fR will have a object \fIvideo\fR available to it\.1572-.1573-.IP "" 01574-.1575-.P1576-The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1577-.1578-.IP "" 41579-.1580-.nf1581-1582-partial(\'theatre/movie\.jade\', { collection: movies });1583-partial(\'theatre/movie\.jade\', movies);1584-partial(\'movie\.jade\', { collection: movies });1585-partial(\'movie\.jade\', movies);1586-partial(\'movie\', movies);1587-// In view: movie\.director1588-.1589-.fi1590-.1591-.IP "" 01592-.1593-.P1594-To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1595-.1596-.IP "" 41597-.1598-.nf1599-1600-partial(\'movie\', { collection: movies, as: \'video\' });1601-// In view: video\.director1602-.1603-.fi1604-.1605-.IP "" 01606-.1607-.P1608-Also we can make our movie the value of \fIthis\fR within our view so that instead of \fImovie\.director\fR we could use \fIthis\.director\fR\.1609-.1610-.IP "" 41611-.1612-.nf1613-1614-partial(\'movie\', { collection: movies, as: this });1615-// In view: this\.director1616-.1617-.fi1618-.1619-.IP "" 01620-.1621-.P1622-Another alternative is to "explode" the properties of the collection item into pseudo globals (local variables) by using \fIas: global\fR, which again is syntactic sugar:1623-.1624-.IP "" 41625-.1626-.nf1627-1628-partial(\'movie\', { collection: movies, as: global });1629-// In view: director1630-.1631-.fi1632-.1633-.IP "" 01634-.1635-.P1636-This same logic applies to a single partial object usage:1637-.1638-.IP "" 41639-.1640-.nf1641-1642-partial(\'movie\', { object: movie, as: this });1643-// In view: this\.director1644-1645-partial(\'movie\', { object: movie, as: global });1646-// In view: director1647-1648-partial(\'movie\', { object: movie, as: \'video\' });1649-// In view: video\.director1650-1651-partial(\'movie\', { object: movie });1652-// In view: movie\.director1653-.1654-.fi1655-.1656-.IP "" 01657-.1658-.P1659-When a non\-collection (does \fInot\fR have \fI\.length\fR) is passed as the second argument, it is assumed to be the \fIobject\fR, after which the object\'s local variable name is derived from the view name:1660-.1661-.IP "" 41662-.1663-.nf1664-1665-partial(\'movie\', movie);1666-// => In view: movie\.director1667-.1668-.fi1669-.1670-.IP "" 01671-.1672-.P1673-This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:1674-.1675-.IP "" 41676-.1677-.nf1678-1679-app\.get(\'/users\', function(req, res){1680- if (req\.xhr) {1681- // respond with the each user in the collection1682- // passed to the "user" view1683- res\.partial(\'user\', users);1684- } else {1685- // respond with layout, and users page1686- // which internally does partial(\'user\', users)1687- // along with other UI1688- res\.render(\'users\', { users: users });1689- }1690-});1691-.1692-.fi1693-.1694-.IP "" 01695-.1696-.SS "res\.local(name[, val])"1697-Get or set the given local variable \fIname\fR\. The locals built up for a response are applied to those given to the view rendering methods such as \fBres\.render()\fR\.1698-.1699-.IP "" 41700-.1701-.nf1702-1703- app\.all(\'/movie/:id\', function(req, res, next){1704- Movie\.get(req\.params\.id, function(err, movie){1705- // Assigns res\.locals\.movie = movie1706- res\.local(\'movie\', movie);1707- });1708- });1709-1710- app\.get(\'/movie/:id\', function(req, res){1711- // movie is already a local, however we1712- // can pass more if we wish1713- res\.render(\'movie\', { displayReviews: true });1714- });1715-.1716-.fi1717-.1718-.IP "" 01719-.1720-.SS "app\.set(name[, val])"1721-Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1722-.1723-.IP "" 41724-.1725-.nf1726-1727-app\.set(\'views\', __dirname + \'/views\');1728-app\.set(\'views\');1729-// => \.\.\.path\.\.\.1730-.1731-.fi1732-.1733-.IP "" 01734-.1735-.P1736-Alternatively you may simply access the settings via \fIapp\.settings\fR:1737-.1738-.IP "" 41739-.1740-.nf1741-1742-app\.settings\.views1743-// => \.\.\.path\.\.\.1744-.1745-.fi1746-.1747-.IP "" 01748-.1749-.SS "app\.enable(name)"1750-Enable the given setting \fIname\fR:1751-.1752-.IP "" 41753-.1754-.nf1755-1756-app\.enable(\'some arbitrary setting\');1757-app\.set(\'some arbitrary setting\');1758-// => true1759-1760-app\.enabled(\'some arbitrary setting\');1761-// => true1762-.1763-.fi1764-.1765-.IP "" 01766-.1767-.SS "app\.enabled(name)"1768-Check if setting \fIname\fR is enabled:1769-.1770-.IP "" 41771-.1772-.nf1773-1774-app\.enabled(\'view cache\');1775-// => false1776-1777-app\.enable(\'view cache\');1778-app\.enabled(\'view cache\');1779-// => true1780-.1781-.fi1782-.1783-.IP "" 01784-.1785-.SS "app\.disable(name)"1786-Disable the given setting \fIname\fR:1787-.1788-.IP "" 41789-.1790-.nf1791-1792-app\.disable(\'some setting\');1793-app\.set(\'some setting\');1794-// => false1795-1796-app\.disabled(\'some setting\');1797-// => false1798-.1799-.fi1800-.1801-.IP "" 01802-.1803-.SS "app\.disabled(name)"1804-Check if setting \fIname\fR is disabled:1805-.1806-.IP "" 41807-.1808-.nf1809-1810-app\.enable(\'view cache\');1811-1812-app\.disabled(\'view cache\');1813-// => false1814-1815-app\.disable(\'view cache\');1816-app\.disabled(\'view cache\');1817-// => true1818-.1819-.fi1820-.1821-.IP "" 01822-.1823-.SS "app\.configure(env|function[, function])"1824-Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1825-.1826-.IP "" 41827-.1828-.nf1829-1830-app\.configure(function(){1831- // executed for each env1832-});1833-1834-app\.configure(\'development\', function(){1835- // executed for \'development\' only1836-});1837-.1838-.fi1839-.1840-.IP "" 01841-.1842-.SS "app\.redirect(name, val)"1843-For use with \fIres\.redirect()\fR we can map redirects at the application level as shown below:1844-.1845-.IP "" 41846-.1847-.nf1848-1849-app\.redirect(\'google\', \'http://google\.com\');1850-.1851-.fi1852-.1853-.IP "" 01854-.1855-.P1856-Now in a route we may call:1857-.1858-.P1859-res\.redirect(\'google\');1860-.1861-.P1862-We may also map dynamic redirects:1863-.1864-.IP "" 41865-.1866-.nf1867-1868-app\.redirect(\'comments\', function(req, res){1869- return \'/post/\' + req\.params\.id + \'/comments\';1870-});1871-.1872-.fi1873-.1874-.IP "" 01875-.1876-.P1877-So now we may do the following, and the redirect will dynamically adjust to the context of the request\. If we called this route with \fIGET /post/12\fR our redirect \fILocation\fR would be \fI/post/12/comments\fR\.1878-.1879-.IP "" 41880-.1881-.nf1882-1883-app\.get(\'/post/:id\', function(req, res){1884- res\.redirect(\'comments\');1885-});1886-.1887-.fi1888-.1889-.IP "" 01890-.1891-.P1892-When mounted, \fIres\.redirect()\fR will respect the mount\-point\. For example if a blog app is mounted at \fI/blog\fR, the following will redirect to \fI/blog/posts\fR:1893-.1894-.IP "" 41895-.1896-.nf1897-1898-res\.redirect(\'/posts\');1899-.1900-.fi1901-.1902-.IP "" 01903-.1904-.SS "app\.error(function)"1905-Adds an error handler \fIfunction\fR which will receive the exception as the first parameter as shown below\. Note that we may set several error handlers by making several calls to this method, however the handler should call \fInext(err)\fR if it does not wish to deal with the exception:1906-.1907-.IP "" 41908-.1909-.nf1910-1911-app\.error(function(err, req, res, next){1912- res\.send(err\.message, 500);1913-});1914-.1915-.fi1916-.1917-.IP "" 01918-.1919-.SS "app\.helpers(obj)"1920-Registers static view helpers\.1921-.1922-.P1923-app\.helpers({1924-.1925-.IP "" 41926-.1927-.nf1928-1929- name: function(first, last){ return first + \', \' + last }1930-, firstName: \'tj\'1931-, lastName: \'holowaychuk\'1932-.1933-.fi1934-.1935-.IP "" 01936-.1937-.P1938-});1939-.1940-.P1941-Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1942-.1943-.IP "" 41944-.1945-.nf1946-1947-<%= name(firstName, lastName) %>1948-.1949-.fi1950-.1951-.IP "" 01952-.1953-.SS "app\.dynamicHelpers(obj)"1954-Registers dynamic view helpers\. Dynamic view helpers are simply functions which accept \fIreq\fR, \fIres\fR, and are evaluated against the \fIServer\fR instance before a view is rendered\. The \fIreturn value\fR of this function becomes the local variable it is associated with\.1955-.1956-.IP "" 41957-.1958-.nf1959-1960-app\.dynamicHelpers({1961- session: function(req, res){1962- return req\.session;1963- }1964-});1965-.1966-.fi1967-.1968-.IP "" 01969-.1970-.P1971-All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1972-.1973-.IP "" 41974-.1975-.nf1976-1977-<%= session\.name %>1978-.1979-.fi1980-.1981-.IP "" 01982-.1983-.SS "app\.mounted(fn)"1984-Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1985-.1986-.IP "" 41987-.1988-.nf1989-1990-var app = express\.createServer(),1991- blog = express\.createServer();1992-1993-blog\.mounted(function(parent){1994- // parent is app1995- // "this" is blog1996-});1997-1998-app\.use(blog);1999-.2000-.fi2001-.2002-.IP "" 02003-.2004-.SS "app\.register(ext, exports)"2005-Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:2006-.2007-.IP "" 42008-.2009-.nf2010-2011- app\.register(\'\.html\', require(\'jade\'));2012-.2013-.fi2014-.2015-.IP "" 02016-.2017-.P2018-This is also useful for libraries that may not match extensions correctly\. For example my haml\.js library is installed from npm as "hamljs" so instead of layout\.hamljs, we can register the engine as "\.haml":2019-.2020-.IP "" 42021-.2022-.nf2023-2024- app\.register(\'\.haml\', require(\'haml\-js\'));2025-.2026-.fi2027-.2028-.IP "" 02029-.2030-.P2031-For engines that do not comply with the Express specification, we can also wrap their api this way\. Below we map \fI\.md\fR to render markdown files, rendering the html once since it will not change on subsequent calls, and support local substitution in the form of "{name}"\.2032-.2033-.IP "" 42034-.2035-.nf2036-2037- app\.register(\'\.md\', {2038- compile: function(str, options){2039- var html = md\.toHTML(str);2040- return function(locals){2041- return html\.replace(/\e{([^}]+)\e}/g, function(_, name){2042- return locals[name];2043- });2044- };2045- }2046- });2047-.2048-.fi2049-.2050-.IP "" 02051-.2052-.SS "app\.listen([port[, host]])"2053-Bind the app server to the given \fIport\fR, which defaults to 3000\. When \fIhost\fR is omitted all connections will be accepted via \fIINADDR_ANY\fR\.2054-.2055-.IP "" 42056-.2057-.nf2058-2059-app\.listen();2060-app\.listen(3000);2061-app\.listen(3000, \'n\.n\.n\.n\');2062-.2063-.fi2064-.2065-.IP "" 02066-.2067-.P2068-The \fIport\fR argument may also be a string representing the path to a unix domain socket:2069-.2070-.IP "" 42071-.2072-.nf2073-2074-app\.listen(\'/tmp/express\.sock\');2075-.2076-.fi2077-.2078-.IP "" 02079-.2080-.P2081-Then try it out:2082-.2083-.IP "" 42084-.2085-.nf2086-2087-$ telnet /tmp/express\.sock2088-GET / HTTP/1\.12089-2090-HTTP/1\.1 200 OK2091-Content\-Type: text/plain2092-Content\-Length: 112093-2094-Hello World2095-.2096-.fi2097-.2098-.IP "" 02099-modified:docs/guide.html+264 added-371 removed
196 unmodified lines197 <li><a href="#Template-Engines">Template Engines</a></li>198 <li><a href="#Session-Support">Session Support</a></li>199 <li><a href="#Migration-Guide">Migration Guide</a></li>200 <li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">201-<li><a href="#req-header-key-defaultValue-">header()</a></li>202-<li><a href="#req-accepts-type-">accepts()</a></li>203-<li><a href="#req-is-type-">is()</a></li>204-<li><a href="#req-param-name-default-">param()</a></li>205-<li><a href="#req-flash-type-msg-">flash()</a></li>201+<li><a href="#req-header-key-defaultValue">header()</a></li>202+<li><a href="#req-accepts-type">accepts()</a></li>203+<li><a href="#req-is-type">is()</a></li>204+<li><a href="#req-param-name-default">param()</a></li>205+<li><a href="#req-flash-type-msg">flash()</a></li>206 <li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>207 </ul></li>208 <li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">209-<li><a href="#res-header-key-val-">header()</a></li>210-<li><a href="#res-contentType-type-">contentType()</a></li>211-<li><a href="#res-attachment-filename-">attachment()</a></li>212-<li><a href="#res-sendfile-path-options-callback-">sendfile()</a></li>213-<li><a href="#res-download-file-filename-callback-">download()</a></li>214-<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>215-<li><a href="#res-redirect-url-status-">redirect()</a></li>216-<li><a href="#res-cookie-name-val-options-">cookie()</a></li>217-<li><a href="#res-clearCookie-name-">clearCookie()</a></li>218-<li><a href="#res-render-view-options-fn-">render()</a></li>219-<li><a href="#res-partial-view-options-">partial()</a></li>220-<li><a href="#res-local-name-val-">local()</a></li>209+<li><a href="#res-header-key-val">header()</a></li>210+<li><a href="#res-charset">charset</a></li>211+<li><a href="#res-contentType-type">contentType()</a></li>212+<li><a href="#res-attachment-filename">attachment()</a></li>213+<li><a href="#res-sendfile-path-options-callback">sendfile()</a></li>214+<li><a href="#res-download-file-filename-callback">download()</a></li>215+<li><a href="#res-send-body-status-headers-status-status">send()</a></li>216+<li><a href="#res-redirect-url-status">redirect()</a></li>217+<li><a href="#res-cookie-name-val-options">cookie()</a></li>218+<li><a href="#res-clearCookie-name">clearCookie()</a></li>219+<li><a href="#res-render-view-options-fn">render()</a></li>220+<li><a href="#res-partial-view-options">partial()</a></li>221+<li><a href="#res-local-name-val">local()</a></li>222+<li><a href="#res-local-obj">local()</a></li>223 </ul></li>224 <li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">223-<li><a href="#app-set-name-val-">set()</a></li>224-<li><a href="#app-enable-name-">enable()</a></li>225-<li><a href="#app-enabled-name-">enabled()</a></li>226-<li><a href="#app-disable-name-">disable()</a></li>227-<li><a href="#app-disabled-name-">disabled()</a></li>228-<li><a href="#app-configure-env-function-function-">configure()</a></li>229-<li><a href="#app-redirect-name-val-">redirect()</a></li>230-<li><a href="#app-error-function-">error()</a></li>231-<li><a href="#app-helpers-obj-">helpers()</a></li>232-<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>233-<li><a href="#app-mounted-fn-">mounted()</a></li>234-<li><a href="#app-register-ext-exports-">register()</a></li>235-<li><a href="#app-listen-port-host-">listen()</a></li>225+<li><a href="#app-set-name-val">set()</a></li>226+<li><a href="#app-enable-name">enable()</a></li>227+<li><a href="#app-enabled-name">enabled()</a></li>228+<li><a href="#app-disable-name">disable()</a></li>229+<li><a href="#app-disabled-name">disabled()</a></li>230+<li><a href="#app-configure-env-function-function">configure()</a></li>231+<li><a href="#app-redirect-name-val">redirect()</a></li>232+<li><a href="#app-error-function">error()</a></li>233+<li><a href="#app-helpers-obj">helpers()</a></li>234+<li><a href="#app-dynamicHelpers-obj">dynamicHelpers()</a></li>235+<li><a href="#app-mounted-fn">mounted()</a></li>236+<li><a href="#app-register-ext-exports">register()</a></li>237+<li><a href="#app-listen-port-host">listen()</a></li>238 </ul></li>239 </ul>240 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 241 <p id="tagline">5 unmodified lines247 <li><a href="guide.html">Guide</a></li>248 <li><a href="screencasts.html">Screencasts</a></li>249 <li><a href="applications.html">Applications</a></li>250 </ul>249-<div class='mp'>250-<h2 id="Express">Express</h2>251-<p class="man-name">252- <code>guide</code>253-</p>251 <h3 id="Installation">Installation</h3>252 256-<pre><code>$ npm install express257-</code></pre>253+<pre><code>$ npm install express</code></pre>254 255 <h3 id="Creating-A-Server">Creating A Server</h3>256 257 <p> To create an instance of the <em>express.HTTPServer</em>, simply invoke the <em>createServer()</em> method. With our instance <em>app</em> we can then define routes based on the HTTP verbs, in this example <em>app.get()</em>.</p>3 unmodified lines261 app.get('/', function(req, res){262 res.send('hello world');263 });264 269-app.listen(3000);270-</code></pre>265+app.listen(3000);</code></pre>266 267 <h3 id="Creating-An-HTTPS-Server">Creating An HTTPS Server</h3>268 269 <p> To initialize a <em>express.HTTPSServer</em> we do the same as above, however we270 pass an options object, accepting <em>key</em>, <em>cert</em> and the others mentioned in node's <a href="http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer">https documentation</a>.</p>271 277-<pre><code> var app = require('express').createServer({ key: ... });278-</code></pre>272+<pre><code> var app = require('express').createServer({ key: ... });</code></pre>273 274 <h3 id="Configuration">Configuration</h3>275 276 <p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers277 can use the <em>configure()</em> method to setup needs required by the current environment. When284-<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment278+<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment 279 prior to the environment specific callback.</p>280 281 <p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces282 in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.283 Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,284 otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>285 286 <pre><code>app.configure(function(){293- app.use(express.methodOverride());294- app.use(express.bodyParser());295- app.use(app.router);287+ app.use(express.methodOverride());288+ app.use(express.bodyParser());289+ app.use(app.router);290 });291 292 app.configure('development', function(){299- app.use(express.static(__dirname + '/public'));300- app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));293+ app.use(express.static(__dirname + '/public'));294+ app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));295 });296 297 app.configure('production', function(){298 var oneYear = 31557600000;305- app.use(express.static({ root: __dirname + '/public', maxAge: oneYear }));299+ app.use(express.static(__dirname + '/public', { maxAge: oneYear }));300 app.use(express.errorHandler());307-});308-</code></pre>301+});</code></pre>302 303 <p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>304 305 <pre><code> app.configure(function(){8 unmodified lines314 // same as app.set('some feature', false);315 316 app.enabled('some feature')317 // => false325- });326-</code></pre>318+ });</code></pre>319 328-<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>320+<p>To alter the environment we can set the <em>NODE</em>ENV_ environment variable, for example:</p>321 330-<pre><code>$ NODE_ENV=production node app.js331-</code></pre>322+<pre><code>$ NODE_ENV=production node app.js</code></pre>323 324 <p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>325 326 <h3 id="Settings">Settings</h3>327 328 <p>Express supports the following settings out of the box:</p>329 339-<ul>340-<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>341-<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>342-<li><em>view engine</em> Default view engine name for views rendered without extensions</li>343-<li><em>view options</em> An object specifying global view options</li>344-</ul>330+<ul><li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li><li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li><li><em>view engine</em> Default view engine name for views rendered without extensions</li><li><em>view options</em> An object specifying global view options</li></ul>331 346-332 <h3 id="Routing">Routing</h3>333 334 <p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.335 For example we may want to render a user's account for the path <em>/user/12</em>, this351-can be done by defining the route below. The values associated to the named placeholders336+can be done by defining the route below. The values associated to the named placeholders 337 are available as <code>req.params</code>.</p>338 339 <pre><code>app.get('/user/:id', function(req, res){355- res.send('user ' + req.params.id);356-});357-</code></pre>340+ res.send('user ' + req.params.id);341+});</code></pre>342 343 <p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example344 when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>345 362-<pre><code>\/user\/([^\/]+)\/?363-</code></pre>346+<pre><code>\/user\/([^\/]+)\/?</code></pre>347 348 <p>Regular expression literals may also be passed for complex uses. Since capture349 groups 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>350 351 <pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){352 res.send(req.params);370-});371-</code></pre>353+});</code></pre>354 355 <p>Curl requests against the previously defined route:</p>356 357 <pre><code> $ curl http://dev:3000/user2 unmodified lines360 [null,null]361 $ curl http://dev:3000/users/1362 ["1",null]363 $ curl http://dev:3000/users/1..15382- ["1","15"]383-</code></pre>364+ ["1","15"]</code></pre>365 366 <p>Below are some route examples, and the associated paths that they367 may consume:</p>368 26 unmodified lines395 /products396 397 "/user/:id.:format?"398 /user/12418- /user/12.json419-</code></pre>399+ /user/12.json</code></pre>400 401 <p>For example we can <strong>POST</strong> some json, and echo the json back using the <em>bodyParser</em> middleware which will parse json request bodies (as well as others), and place the result in <em>req.body</em>:</p>402 403 <pre><code>var express = require('express')4 unmodified lines408 app.post('/', function(req, res){409 res.send(req.body);410 });411 432-app.listen(3000);433-</code></pre>412+app.listen(3000);</code></pre>413 414 <p>Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, 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>415 416 <h3 id="Passing-Route-Control">Passing Route Control</h3>2 unmodified lines419 the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,420 and middleware continue to be invoked in the order that they are added via <em>use()</em>. 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> and decides to respond.</p>421 422 <pre><code>app.get('/users/:id?', function(req, res, next){444- var id = req.params.id;445- if (id) {446- // do something447- } else {448- next();449- }423+ var id = req.params.id;424+ if (id) {425+ // do something426+ } else {427+ next();428+ }429 });430 431 app.get('/users', function(req, res){453- // do something else454-});455-</code></pre>432+ // do something else433+});</code></pre>434 435 <p>The <em>app.all()</em> method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to <em>req.user</em>.</p>436 437 <pre><code>var express = require('express')25 unmodified lines463 app.get('*', function(req, res){464 res.send('what???', 404);465 });466 489-app.listen(3000); 490-</code></pre>467+app.listen(3000); </code></pre>468 469 <h3 id="Middleware">Middleware</h3>470 471 <p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be1 unmodified line473 474 <pre><code> var express = require('express');475 476 var app = express.createServer(500- express.logger()501- , express.bodyParser()502- );503-</code></pre>477+ express.logger()478+ , express.bodyParser()479+ );</code></pre>480 481 <p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>482 507-<pre><code>app.use(express.logger({ format: ':method :uri' }));508-</code></pre>483+<pre><code>app.use(express.logger({ format: ':method :uri' }));</code></pre>484 485 <p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>486 487 <pre><code>var connect = require('connect');488 app.use(connect.logger());514-app.use(connect.bodyParser());515-</code></pre>489+app.use(connect.bodyParser());</code></pre>490 491 <p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>492 493 <pre><code>app.use(express.logger());520-app.use(express.bodyParser());521-</code></pre>494+app.use(express.bodyParser());</code></pre>495 496 <h3 id="Route-Middleware">Route Middleware</h3>497 498 <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>499 527-<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>500+<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user. </p>501 502 <pre><code>app.get('/user/:id', function(req, res, next){503 loadUser(req.params.id, function(err, user){504 if (err) return next(err);505 res.send('Viewing user ' + user.name);506 });534-});535-</code></pre>507+});</code></pre>508 537-<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>509+<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>510 511 <pre><code>function loadUser(req, res, next) {512 // You would fetch your user from the db513 var user = users[req.params.id];6 unmodified lines520 }521 522 app.get('/user/:id', loadUser, function(req, res){523 res.send('Viewing user ' + req.user.name);552-});553-</code></pre>524+});</code></pre>525 526 <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>527 528 <pre><code>function andRestrictToSelf(req, res, next) {3 unmodified lines532 }533 534 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){535 res.send('Editing user ' + req.user.name);565-});566-</code></pre>536+});</code></pre>537 538 <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>539 540 <pre><code>function andRestrictTo(role) {5 unmodified lines546 }547 548 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){549 res.send('Deleted user ' + req.user.name);580-});581-</code></pre>550+});</code></pre>551 552 <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>553 554 <pre><code>var a = [middleware1, middleware2]4 unmodified lines559 app.get('/bar', a, function(){});560 561 app.get('/', a, middleware3, middleware4, function(){});562 app.get('/', a, b, function(){});594-app.get('/', all, function(){});595-</code></pre>563+app.get('/', all, function(){});</code></pre>564 565 <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>566 567 <h3 id="HTTP-Methods">HTTP Methods</h3>5 unmodified lines573 <pre><code> <form method="post" action="/">574 <input type="text" name="user[name]" />575 <input type="text" name="user[email]" />576 <input type="submit" value="Submit" />609- </form>610-</code></pre>577+ </form></code></pre>578 579 <p>By default Express does not know what to do with this request body, so we should add the <em>bodyParser</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> and <em>application/json</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>580 614-<pre><code>app.use(express.bodyParser());615-</code></pre>581+<pre><code>app.use(express.bodyParser());</code></pre>582 583 <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>584 585 <pre><code>app.post('/', function(req, res){586 console.log(req.body.user);587 res.redirect('back');622-});623-</code></pre>588+});</code></pre>589 590 <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>bodyParser</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>591 592 <pre><code>app.use(express.bodyParser());628-app.use(express.methodOverride());629-</code></pre>593+app.use(express.methodOverride());</code></pre>594 595 <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>596 597 <pre><code><form method="post" action="/">5 unmodified lines603 604 app.put('/', function(){605 console.log(req.body.user);606 res.redirect('back');643-});644-</code></pre>607+});</code></pre>608 609 <h3 id="Error-Handling">Error Handling</h3>610 611 <p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,13 unmodified lines625 });626 627 app.get('/500', function(req, res){628 throw new Error('keyboard cat!');666-});667-</code></pre>629+});</code></pre>630 631 <p>We can call <em>app.error()</em> several times as shown below.632 Here we check for an instanceof <em>NotFound</em> and show the633 404 page, or we pass on to the next error handler.</p>634 635 <p>Note that these handlers can be defined anywhere, as they674-will be placed below the route handlers on <em>listen()</em>. This636+will be placed below the route handlers on <em>listen()</em>. This 637 allows for definition within <em>configure()</em> blocks so we can638 handle exceptions in different ways based on the environment.</p>639 640 <pre><code>app.error(function(err, req, res, next){1 unmodified line642 res.render('404.jade');643 } else {644 next(err);645 }684-});685-</code></pre>646+});</code></pre>647 648 <p>Here we assume all errors as 500 for the simplicity of649 this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the <em>error.code</em> of <em>ENOENT</em>, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.</p>650 651 <pre><code>app.error(function(err, req, res){652 res.render('500.jade', {653 error: err654 });694-});695-</code></pre>655+});</code></pre>656 657 <p>Our apps could also utilize the Connect <em>errorHandler</em> middleware698-to report on exceptions. For example if we wish to output exceptions658+to report on exceptions. For example if we wish to output exceptions 659 in "development" mode to <em>stderr</em> we can use:</p>660 701-<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));702-</code></pre>661+<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));</code></pre>662 663 <p>Also during development we may want fancy html pages to show exceptions664 that are passed or thrown, so we can set <em>showStack</em> to true:</p>665 707-<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));708-</code></pre>666+<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));</code></pre>667 668 <p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>669 is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>670 5 unmodified lines676 User.get(req.params.userId, function(err, user){677 if (err) return next(err);678 res.send('user ' + user.name);679 });722-}); 723-</code></pre>680+}); </code></pre>681 682 <p>With preconditions our params 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>683 684 <pre><code>app.param('userId', function(req, res, next, id){2 unmodified lines687 if (!user) return next(new Error('failed to find user'));688 req.user = user;689 next();690 });734-});735-</code></pre>691+});</code></pre>692 693 <p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>694 695 <pre><code>app.get('/user/:userId', function(req, res){696 res.send('user ' + req.user.name);741-});742-</code></pre>697+});</code></pre>698 699 <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>700 746-<pre><code>app.param('number', function(n){ return parseInt(n, 10); });747-</code></pre>701+<pre><code>app.param('number', function(n){ return parseInt(n, 10); });</code></pre>702 703 <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>704 751-<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });752-</code></pre>705+<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });</code></pre>706 707 <h3 id="View-Rendering">View Rendering</h3>708 756-<p>View filenames take the form "<name>.<engine>", where <engine> is the name709+<p>View filenames take the form "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name710 of the module that will be required. For example the view <em>layout.ejs</em> will711 tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.compile(str, options)</em>, and return a <em>Function</em> to comply with Express. To alter this behaviour712 <em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.</p>713 714 <p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,762-and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as715+and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as 716 the <em>body</em> local variable in <em>layout.jade</em>.</p>717 718 <pre><code>app.get('/', function(req, res){766- res.render('index.jade', { title: 'My Site' });767-});768-</code></pre>719+ res.render('index.jade', { title: 'My Site' });720+});</code></pre>721 722 <p>The new <em>view engine</em> setting allows us to specify our default template engine,723 so for example when using jade we could set:</p>724 773-<pre><code>app.set('view engine', 'jade');774-</code></pre>725+<pre><code>app.set('view engine', 'jade');</code></pre>726 727 <p>Allowing us to render with:</p>728 778-<pre><code>res.render('index');779-</code></pre>729+<pre><code>res.render('index');</code></pre>730 731 <p>vs:</p>732 783-<pre><code>res.render('index.jade');784-</code></pre>733+<pre><code>res.render('index.jade');</code></pre>734 735 <p>When <em>view engine</em> is set, extensions are entirely optional, however we can still736 mix and match template engines:</p>737 789-<pre><code>res.render('another-page.ejs');790-</code></pre>738+<pre><code>res.render('another-page.ejs');</code></pre>739 740 <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>741 742 <pre><code>app.set('view options', {743 layout: false796-});797-</code></pre>744+});</code></pre>745 746 <p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>747 801-<pre><code>res.render('myview.ejs', { layout: true });802-</code></pre>748+<pre><code>res.render('myview.ejs', { layout: true });</code></pre>749 750 <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>751 806-<pre><code>res.render('page', { layout: 'mylayout' });807-</code></pre>752+<pre><code>res.render('page', { layout: 'mylayout' });</code></pre>753 754 <p>Otherwise we must specify the extension:</p>755 811-<pre><code>res.render('page', { layout: 'mylayout.jade' });812-</code></pre>756+<pre><code>res.render('page', { layout: 'mylayout.jade' });</code></pre>757 758 <p>These paths may also be absolute:</p>759 816-<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });817-</code></pre>760+<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });</code></pre>761 762 <p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>763 764 <pre><code>app.set('view options', {765 open: '{{',766 close: '}}'824-});825-</code></pre>767+});</code></pre>768 769 <h3 id="View-Partials">View Partials</h3>770 771 <p>The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating830-in a view to display comments, we would use a partial with collection support:</p>772+in a view to display comments, we could use partial collection:</p>773 832-<pre><code>partial('comment', { collection: comments });833-</code></pre>774+<pre><code>partial('comment', { collection: comments });</code></pre>775 835-<p>If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>776+<p>If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>777 837-<pre><code>partial('comment', comments);838-</code></pre>778+<pre><code>partial('comment', comments);</code></pre>779 840-<p>When using the partial collection support a few "magic" variables are provided780+<p>When using the partial collection support a few "magic" locals are provided781 for free:</p>782 843-<ul>844-<li><em>firstInCollection</em> true if this is the first object</li>845-<li><em>indexInCollection</em> index of the object in the collection</li>846-<li><em>lastInCollection</em> true if this is the last object</li>847-<li><em>collectionLength</em> length of the collection</li>848-</ul>783+<ul><li><em>firstInCollection</em> true if this is the first object</li><li><em>indexInCollection</em> index of the object in the collection</li><li><em>lastInCollection</em> true if this is the last object</li><li><em>collectionLength</em> length of the collection</li></ul>784 850-785 <p>Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well. So for example if we were to render a blog post with <em>partial('blog/post', post)</em> it would generate the <em>post</em> local, but the view calling this function had the local <em>user</em>, it would be available to the <em>blog/post</em> view as well.</p>786 787 <p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>788 10 unmodified lines799 <h3 id="Template-Engines">Template Engines</h3>800 801 <p>Below are a few template engines commonly used with Express:</p>802 869-<ul>870-<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>871-<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>872-<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>873-<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>874-</ul>803+<ul><li><a href="http://github.com/visionmedia/haml.js">Haml</a> haml implementation</li><li><a href="http://jade-lang.com">Jade</a> haml.js successor</li><li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li><li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li><li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li></ul>804 876-805 <h3 id="Session-Support">Session Support</h3>806 807 <p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieParser</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>808 809 <pre><code>app.use(express.cookieParser());882-app.use(express.session({ secret: "keyboard cat" }));883-</code></pre>810+app.use(express.session({ secret: "keyboard cat" }));</code></pre>811 812 <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>813 814 <pre><code>var RedisStore = require('connect-redis');815 app.use(express.cookieParser());889-app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));890-</code></pre>816+app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));</code></pre>817 818 <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>819 820 <pre><code>var RedisStore = require('connect-redis');16 unmodified lines837 if (req.session.items && req.session.items.length) {838 req.flash('info', 'You have %s items in your cart', req.session.items.length);839 }840 res.render('shopping-cart');915-});916-</code></pre>841+});</code></pre>842 843 <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/middleware-session.html">Connect Session</a> documentation.</p>844 845 <h3 id="Migration-Guide">Migration Guide</h3>846 847 <p> Express 1.x developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application to work with Express 2.x, Connect 1.x, and Node 0.4.x.</p>848 924-<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>849+<h3 id="req-header-key-defaultValue">req.header(key[, defaultValue])</h3>850 851 <p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>852 853 <pre><code>req.header('Host');854 req.header('host');930-req.header('Accept', '*/*');931-</code></pre>855+req.header('Accept', '*/*');</code></pre>856 857 <p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>858 859 <pre><code>// sent Referrer: http://google.com1 unmodified line861 req.header('Referer');862 // => "http://google.com"863 864 req.header('Referrer');941-// => "http://google.com"942-</code></pre>865+// => "http://google.com"</code></pre>866 944-<h3 id="req-accepts-type-">req.accepts(type)</h3>867+<h3 id="req-accepts-type">req.accepts(type)</h3>868 869 <p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>870 871 <p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise13 unmodified lines885 // => true886 887 req.accepts('image/png');888 req.accepts('png');966-// => false967-</code></pre>889+// => false</code></pre>890 969-<h3 id="req-is-type-">req.is(type)</h3>891+<h3 id="req-is-type">req.is(type)</h3>892 893 <p>Check if the incoming request contains the <em>Content-Type</em>894 header field, and it contains the give mime <em>type</em>.</p>895 7 unmodified lines903 req.is('application/json');904 // => true905 906 req.is('html');985- // => false986-</code></pre>907+ // => false</code></pre>908 909 <p>Ad-hoc callbacks can also be registered with Express, to perform910 assertions again the request, for example if we need an expressive911 way to check if our incoming request is an image, we can register <em>"an image"</em>912 callback:</p>913 914 <pre><code> app.is('an image', function(req){915 return 0 == req.headers['content-type'].indexOf('image');995- });996-</code></pre>916+ });</code></pre>917 918 <p>Now within our route callbacks, we can use to to assert content types919 such as <em>"image/jpeg"</em>, <em>"image/png"</em>, etc.</p>920 2 unmodified lines923 // do something924 } else {925 next();926 }1007- });1008-</code></pre>927+ });</code></pre>928 929 <p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you930 can perform any request assertion you wish.</p>931 932 <p>Wildcard matches can also be made, simplifying our example above for <em>"an image"</em>, by asserting the <em>subtype</em> only:</p>933 1015-<pre><code>req.is('image/*');1016-</code></pre>934+<pre><code>req.is('image/*');</code></pre>935 936 <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>937 1020-<pre><code>req.is('*/json');1021-</code></pre>938+<pre><code>req.is('*/json');</code></pre>939 1023-<h3 id="req-param-name-default-">req.param(name[, default])</h3>940+<h3 id="req-param-name-default">req.param(name[, default])</h3>941 942 <p>Return the value of param <em>name</em> when present or <em>default</em>.</p>943 1027-<ul>1028-<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>1029-<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1030-<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1031-</ul>944+<ul><li>Checks route params (<em>req.params</em>), ex: /user/:id</li><li>Checks query string params (<em>req.query</em>), ex: ?id=12</li><li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li></ul>945 1033-946 <p>To utilize urlencoded request bodies, <em>req.body</em>947 should be an object. This can be done by using948 the _express.bodyParser middleware.</p>949 1038-<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>950+<h3 id="req-flash-type-msg">req.flash(type[, msg])</h3>951 952 <p>Queue flash <em>msg</em> of the given <em>type</em>.</p>953 954 <pre><code>req.flash('info', 'email sent');7 unmodified lines962 req.flash('info');963 // => []964 965 req.flash();1054-// => { error: ['email delivery failed'], info: [] }1055-</code></pre>966+// => { error: ['email delivery failed'], info: [] }</code></pre>967 968 <p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>969 1059-<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1060-</code></pre>970+<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);</code></pre>971 972 <h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>973 974 <p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header975 to see if it was issued by an <em>XMLHttpRequest</em>:</p>976 977 <pre><code>req.xhr1068-req.isXMLHttpRequest1069-</code></pre>978+req.isXMLHttpRequest</code></pre>979 1071-<h3 id="res-header-key-val-">res.header(key[, val])</h3>980+<h3 id="res-header-key-val">res.header(key[, val])</h3>981 982 <p>Get or set the response header <em>key</em>.</p>983 984 <pre><code>res.header('Content-Length');2 unmodified lines987 res.header('Content-Length', 123);988 // => 123989 990 res.header('Content-Length');1082-// => 1231083-</code></pre>991+// => 123</code></pre>992 1085-<h3 id="res-contentType-type-">res.contentType(type)</h3>993+<h3 id="res-charset">res.charset</h3>994 995+<p>Sets the charset for subsequent <code>Content-Type</code> header fields. For example <code>res.send()</code> and <code>res.render()</code> default to "utf8", so we may explicitly set the charset before rendering a template:</p>996+997+<pre><code>res.charset = 'ISO-8859-1';998+res.render('users');</code></pre>999+1000+<p>or before responding with <code>res.send()</code>:</p>1001+1002+<pre><code>res.charset = 'ISO-8859-1';1003+res.send(str);</code></pre>1004+1005+<p>or with node's <code>res.end()</code>:</p>1006+1007+<pre><code>res.charset = 'ISO-8859-1';1008+res.header('Content-Type', 'text/plain');1009+res.end(str);</code></pre>1010+1011+<h3 id="res-contentType-type">res.contentType(type)</h3>1012+1013 <p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>1014 1015 <pre><code> var filename = 'path/to/image.png';1016 res.contentType(filename);1091- // Content-Type is now "image/png"1092-</code></pre>1017+ // Content-Type is now "image/png"</code></pre>1018 1094-<h3 id="res-attachment-filename-">res.attachment([filename])</h3>1019+<p>A literal <em>Content-Type</em> works as well:</p>1020 1021+<pre><code> res.contentType('application/json');</code></pre>1022+1023+<p>Or simply the extension without leading <code>.</code>:</p>1024+1025+<pre><code> res.contentType('json');</code></pre>1026+1027+<h3 id="res-attachment-filename">res.attachment([filename])</h3>1028+1029 <p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>1030 1098-<pre><code> res.attachment('path/to/my/image.png');1099-</code></pre>1031+<pre><code> res.attachment('path/to/my/image.png');</code></pre>1032 1101-<h3 id="res-sendfile-path-options-callback-">res.sendfile(path[, options[, callback]])</h3>1033+<h3 id="res-sendfile-path-options-callback">res.sendfile(path[, options[, callback]])</h3>1034 1103-<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>1035+<p>Used by <code>res.download()</code> to transfer an arbitrary file. </p>1036 1105-<pre><code>res.sendfile('path/to/my.file');1106-</code></pre>1037+<pre><code>res.sendfile('path/to/my.file');</code></pre>1038 1039 <p>This method accepts an optional callback which is called when1040 an error occurs, or when the transfer is complete. By default failures call <code>next(err)</code>, however when a callback is supplied you must do this explicitly, or act on the error.</p>1041 2 unmodified lines1044 next(err);1045 } else {1046 console.log('transferred %s', path);1047 }1117-});1118-</code></pre>1048+});</code></pre>1049 1050 <p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>1051 1052 <pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1053 // handle1124-});1125-</code></pre>1054+});</code></pre>1055 1127-<h3 id="res-download-file-filename-callback-">res.download(file[, filename[, callback]])</h3>1056+<h3 id="res-download-file-filename-callback">res.download(file[, filename[, callback]])</h3>1057 1058 <p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>1059 1060 <pre><code>res.download('path/to/image.png');1132-res.download('path/to/image.png', 'foo.png');1133-</code></pre>1061+res.download('path/to/image.png', 'foo.png');</code></pre>1062 1063 <p>This is equivalent to:</p>1064 1065 <pre><code>res.attachment(file);1138-res.sendfile(file);1139-</code></pre>1066+res.sendfile(file);</code></pre>1067 1068 <p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>:</p>1069 1070 <pre><code>res.download(path, 'expenses.doc', function(err){1071 // handle1145-});1146-</code></pre>1072+});</code></pre>1073 1148-<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>1074+<h3 id="res-send-body-status-headers-status-status">res.send(body|status[, headers|status[, status]])</h3>1075 1076 <p>The <em>res.send()</em> method is a high level response utility allowing you to pass1077 objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>1078 2 unmodified lines1081 res.send({ some: 'json' });1082 res.send('<p>some html</p>');1083 res.send('Sorry, cant find that', 404);1084 res.send('text', { 'Content-Type': 'text/plain' }, 201);1159- res.send(404);1160-</code></pre>1085+ res.send(404);</code></pre>1086 1087 <p>By default the <em>Content-Type</em> response header is set, however if explicitly1088 assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1089 it will not be set again.</p>1090 1091 <p>Note that this method <em>end()</em>s the response, so you will want to use node's <em>res.write()</em> for multiple writes or streaming.</p>1092 1168-<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>1093+<h3 id="res-redirect-url-status">res.redirect(url[, status])</h3>1094 1095 <p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>1096 1097 <pre><code>res.redirect('/', 301);1098 res.redirect('/account');1099 res.redirect('http://google.com');1100 res.redirect('home');1176-res.redirect('back');1177-</code></pre>1101+res.redirect('back');</code></pre>1102 1103 <p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1104 The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1105 the "home" setting and defaults to "/".</p>1106 1183-<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>1107+<h3 id="res-cookie-name-val-options">res.cookie(name, val[, options])</h3>1108 1109 <p>Sets the given cookie <em>name</em> to <em>val</em>, with options <em>httpOnly</em>, <em>secure</em>, <em>expires</em> etc.</p>1110 1111 <pre><code>// "Remember me" for 15 minutes 1188-res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1189-</code></pre>1112+res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });</code></pre>1113 1114 <p>The <em>maxAge</em> property may be used to set <em>expires</em> relative to <em>Date.now()</em> in milliseconds, so our example above can now become:</p>1115 1193-<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });1194-</code></pre>1116+<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });</code></pre>1117 1118 <p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>1119 1120 <pre><code>app.use(express.cookieParser());1121 1122 app.get('/', function(req, res){1123 // use req.cookies.rememberme1202-});1203-</code></pre>1124+});</code></pre>1125 1205-<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>1126+<h3 id="res-clearCookie-name">res.clearCookie(name)</h3>1127 1128 <p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>1129 1209-<pre><code>res.clearCookie('rememberme');1210-</code></pre>1130+<pre><code>res.clearCookie('rememberme');</code></pre>1131 1212-<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>1132+<h3 id="res-render-view-options-fn">res.render(view[, options[, fn]])</h3>1133 1134 <p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1135 When a callback function is given a response will <em>not</em> be made1136 automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>1137 1138 <p>The <em>options</em> passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:</p>1139 1140 <pre><code>var user = { name: 'tj' };1221-res.render('index', { layout: false, user: user });1222-</code></pre>1141+res.render('index', { layout: false, user: user });</code></pre>1142 1224-<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>1143+<h3 id="res-partial-view-options">res.partial(view[, options])</h3>1144 1145 <p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1146 to the view as a local variable.</p>1147 1229-<ul>1230-<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1231-<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>1148+<ul><li><em>object</em> the object named by <em>as</em> or derived from the view name</li><li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p><ul><li>as: 'something' will add the <em>something</em> local variable</li><li>as: this will use the collection value as the template context</li><li><p>as: global will merge the collection value's properties with <em>locals</em></p></li></ul></li><li><p><em>collection</em> Array of objects, the name is derived from the view name itself. 1149+For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li></ul>1150 1233-<ul>1234-<li>as: 'something' will add the <em>something</em> local variable</li>1235-<li>as: this will use the collection value as the template context</li>1236-<li>as: global will merge the collection value's properties with <em>locals</em></li>1237-</ul>1238-</li>1239-<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1240-For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1241-</ul>1242-1243-1151 <p>The following are equivalent, and the name of collection value when passed1152 to the partial will be <em>movie</em> as derived from the name.</p>1153 1154 <pre><code>partial('theatre/movie.jade', { collection: movies });1155 partial('theatre/movie.jade', movies);1156 partial('movie.jade', { collection: movies });1157 partial('movie.jade', movies);1158 partial('movie', movies);1252-// In view: movie.director1253-</code></pre>1159+// In view: movie.director</code></pre>1160 1161 <p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>1162 1163 <pre><code>partial('movie', { collection: movies, as: 'video' });1258-// In view: video.director1259-</code></pre>1164+// In view: video.director</code></pre>1165 1166 <p>Also we can make our movie the value of <em>this</em> within our view so that instead1167 of <em>movie.director</em> we could use <em>this.director</em>.</p>1168 1169 <pre><code>partial('movie', { collection: movies, as: this });1265-// In view: this.director1266-</code></pre>1170+// In view: this.director</code></pre>1171 1268-<p>Another alternative is to "explode" the properties of the collection item into1172+<p>Another alternative is to "expand" the properties of the collection item into1173 pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>1174 1175 <pre><code>partial('movie', { collection: movies, as: global });1272-// In view: director1273-</code></pre>1176+// In view: director</code></pre>1177 1178 <p>This same logic applies to a single partial object usage:</p>1179 1180 <pre><code>partial('movie', { object: movie, as: this });5 unmodified lines1186 partial('movie', { object: movie, as: 'video' });1187 // In view: video.director1188 1189 partial('movie', { object: movie });1287-// In view: movie.director1288-</code></pre>1190+// In view: movie.director</code></pre>1191 1192 <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>1193 1292-<pre><code>partial('movie', movie);1293-// => In view: movie.director1294-</code></pre>1194+<pre><code>var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1195+partial('movie', movie)1196+// => In view: movie.director</code></pre>1197 1198+<p>The exception of this, is when a "plain" object, aka "{}" or "new Object" is passed, which is considered an object with local variable. For example some may expect a "movie" local with the following, however since it is a plain object "director" and "title" are simply locals:</p>1199+1200+<pre><code>var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1201+partial('movie', movie)</code></pre>1202+1203+<p>For cases like this where passing a plain object is desired, simply assign it to a key, or use the <code>object</code> key which will use the filename-derived variable name. The examples below are equivalent:</p>1204+1205+<pre><code> partial('movie', { locals: { movie: movie }})1206+ partial('movie', { movie: movie })1207+ partial('movie', { object: movie })</code></pre>1208+1209 <p>This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:</p>1210 1211 <pre><code>app.get('/users', function(req, res){1212 if (req.xhr) {5 unmodified lines1218 // which internally does partial('user', users)1219 // along with other UI1220 res.render('users', { users: users });1221 }1309-});1310-</code></pre>1222+});</code></pre>1223 1312-<h3 id="res-local-name-val-">res.local(name[, val])</h3>1224+<h3 id="res-local-name-val">res.local(name[, val])</h3>1225 1226 <p>Get or set the given local variable <em>name</em>. The locals built up for a response are applied to those given to the view rendering methods such as <code>res.render()</code>.</p>1227 1228 <pre><code> app.all('/movie/:id', function(req, res, next){6 unmodified lines1235 app.get('/movie/:id', function(req, res){1236 // movie is already a local, however we1237 // can pass more if we wish1238 res.render('movie', { displayReviews: true });1327- });1328-</code></pre>1239+ });</code></pre>1240 1330-<h3 id="app-set-name-val-">app.set(name[, val])</h3>1241+<h3 id="res-local-obj">res.local(obj)</h3>1242 1243+<p> Assign several locals with the given <em>obj</em>. The following are equivalent:</p>1244+1245+<pre><code> res.local('foo', bar);1246+ res.local('bar', baz);1247+1248+ res.locals({ foo: bar, bar, baz });</code></pre>1249+1250+<h3 id="app-set-name-val">app.set(name[, val])</h3>1251+1252 <p>Apply an application level setting <em>name</em> to <em>val</em>, or1253 get the value of <em>name</em> when <em>val</em> is not present:</p>1254 1255 <pre><code>app.set('views', __dirname + '/views');1256 app.set('views');1337-// => ...path...1338-</code></pre>1257+// => ...path...</code></pre>1258 1259 <p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>1260 1261 <pre><code>app.settings.views1343-// => ...path...1344-</code></pre>1262+// => ...path...</code></pre>1263 1346-<h3 id="app-enable-name-">app.enable(name)</h3>1264+<h3 id="app-enable-name">app.enable(name)</h3>1265 1266 <p>Enable the given setting <em>name</em>:</p>1267 1268 <pre><code>app.enable('some arbitrary setting');1269 app.set('some arbitrary setting');1270 // => true1271 1272 app.enabled('some arbitrary setting');1355-// => true1356-</code></pre>1273+// => true</code></pre>1274 1358-<h3 id="app-enabled-name-">app.enabled(name)</h3>1275+<h3 id="app-enabled-name">app.enabled(name)</h3>1276 1277 <p>Check if setting <em>name</em> is enabled:</p>1278 1279 <pre><code>app.enabled('view cache');1280 // => false1281 1282 app.enable('view cache');1283 app.enabled('view cache');1367-// => true1368-</code></pre>1284+// => true</code></pre>1285 1370-<h3 id="app-disable-name-">app.disable(name)</h3>1286+<h3 id="app-disable-name">app.disable(name)</h3>1287 1288 <p>Disable the given setting <em>name</em>:</p>1289 1290 <pre><code>app.disable('some setting');1291 app.set('some setting');1292 // => false1293 1294 app.disabled('some setting');1379-// => false1380-</code></pre>1295+// => false</code></pre>1296 1382-<h3 id="app-disabled-name-">app.disabled(name)</h3>1297+<h3 id="app-disabled-name">app.disabled(name)</h3>1298 1299 <p>Check if setting <em>name</em> is disabled:</p>1300 1301 <pre><code>app.enable('view cache');2 unmodified lines1304 // => false1305 1306 app.disable('view cache');1307 app.disabled('view cache');1393-// => true1394-</code></pre>1308+// => true</code></pre>1309 1396-<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>1310+<h3 id="app-configure-env-function-function">app.configure(env|function[, function])</h3>1311 1312 <p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>1313 1314 <pre><code>app.configure(function(){1 unmodified line1316 });1317 1318 app.configure('development', function(){1319 // executed for 'development' only1406-});1407-</code></pre>1320+});</code></pre>1321 1409-<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>1322+<h3 id="app-redirect-name-val">app.redirect(name, val)</h3>1323 1324 <p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>1325 1413-<pre><code>app.redirect('google', 'http://google.com');1414-</code></pre>1326+<pre><code>app.redirect('google', 'http://google.com');</code></pre>1327 1328 <p>Now in a route we may call:</p>1329 1330 <p> res.redirect('google');</p>1 unmodified line1332 <p>We may also map dynamic redirects:</p>1333 1334 <pre><code>app.redirect('comments', function(req, res){1335 return '/post/' + req.params.id + '/comments';1424-});1425-</code></pre>1336+});</code></pre>1337 1338 <p>So now we may do the following, and the redirect will dynamically adjust to1339 the context of the request. If we called this route with <em>GET /post/12</em> our1340 redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>1341 1342 <pre><code>app.get('/post/:id', function(req, res){1343 res.redirect('comments');1433-});1434-</code></pre>1344+});</code></pre>1345 1346 <p>When mounted, <em>res.redirect()</em> will respect the mount-point. For example if a blog app is mounted at <em>/blog</em>, the following will redirect to <em>/blog/posts</em>:</p>1347 1438-<pre><code>res.redirect('/posts');1439-</code></pre>1348+<pre><code>res.redirect('/posts');</code></pre>1349 1441-<h3 id="app-error-function-">app.error(function)</h3>1350+<h3 id="app-error-function">app.error(function)</h3>1351 1352 <p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1353 Note that we may set several error handlers by making several calls to this method, however the handler1354 should call <em>next(err)</em> if it does not wish to deal with the exception:</p>1355 1356 <pre><code>app.error(function(err, req, res, next){1357 res.send(err.message, 500);1449-});1450-</code></pre>1358+});</code></pre>1359 1452-<h3 id="app-helpers-obj-">app.helpers(obj)</h3>1360+<h3 id="app-helpers-obj">app.helpers(obj)</h3>1361 1362 <p>Registers static view helpers.</p>1363 1456-<p> app.helpers({</p>1364+<p> app.helpers({1365+ name: function(first, last){ return first + ', ' + last }1366+ , firstName: 'tj'1367+ , lastName: 'holowaychuk'1368+ });</p>1369 1458-<pre><code> name: function(first, last){ return first + ', ' + last }1459-, firstName: 'tj'1460-, lastName: 'holowaychuk'1461-</code></pre>1462-1463-<p> });</p>1464-1370 <p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1371 as well as the <em>name()</em> function exposed.</p>1372 1468-<pre><code><%= name(firstName, lastName) %>1469-</code></pre>1373+<pre><code><%= name(firstName, lastName) %></code></pre>1374 1471-<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>1375+<h3 id="app-dynamicHelpers-obj">app.dynamicHelpers(obj)</h3>1376 1377 <p>Registers dynamic view helpers. Dynamic view helpers1378 are simply functions which accept <em>req</em>, <em>res</em>, and are1379 evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function2 unmodified lines1382 <pre><code>app.dynamicHelpers({1383 session: function(req, res){1384 return req.session;1385 }1482-});1483-</code></pre>1386+});</code></pre>1387 1388 <p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>1389 1487-<pre><code><%= session.name %>1488-</code></pre>1390+<pre><code><%= session.name %></code></pre>1391 1490-<h3 id="app-mounted-fn-">app.mounted(fn)</h3>1392+<h3 id="app-mounted-fn">app.mounted(fn)</h3>1393 1394 <p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>1395 1396 <pre><code>var app = express.createServer(),3 unmodified lines1400 // parent is app1401 // "this" is blog1402 });1403 1502-app.use(blog);1503-</code></pre>1404+app.use(blog);</code></pre>1405 1505-<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>1406+<h3 id="app-register-ext-exports">app.register(ext, exports)</h3>1407 1408 <p>Register the given template engine <em>exports</em>1409 as <em>ext</em>. For example we may wish to map ".html"1410 files to jade:</p>1411 1511-<pre><code> app.register('.html', require('jade'));1512-</code></pre>1412+<pre><code> app.register('.html', require('jade'));</code></pre>1413 1414 <p>This is also useful for libraries that may not1415 match extensions correctly. For example my haml.js1416 library is installed from npm as "hamljs" so instead1417 of layout.hamljs, we can register the engine as ".haml":</p>1418 1519-<pre><code> app.register('.haml', require('haml-js'));1520-</code></pre>1419+<pre><code> app.register('.haml', require('haml-js'));</code></pre>1420 1421 <p>For engines that do not comply with the Express1422 specification, we can also wrap their api this way. Below1423 we map <em>.md</em> to render markdown files, rendering the html once8 unmodified lines1432 return locals[name];1433 });1434 };1435 }1537- });1538-</code></pre>1436+ });</code></pre>1437 1540-<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>1438+<h3 id="app-listen-port-host">app.listen([port[, host]])</h3>1439 1440 <p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1543-connections will be accepted via <em>INADDR_ANY</em>.</p>1441+connections will be accepted via <em>INADDR</em>ANY_.</p>1442 1443 <pre><code>app.listen();1444 app.listen(3000);1547-app.listen(3000, 'n.n.n.n');1548-</code></pre>1445+app.listen(3000, 'n.n.n.n');</code></pre>1446 1447 <p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>1448 1552-<pre><code>app.listen('/tmp/express.sock');1553-</code></pre>1449+<pre><code>app.listen('/tmp/express.sock');</code></pre>1450 1451 <p>Then try it out:</p>1452 1453 <pre><code>$ telnet /tmp/express.sock2 unmodified lines1456 HTTP/1.1 200 OK1457 Content-Type: text/plain1458 Content-Length: 111459 1564-Hello World1565-</code></pre>1566-1567-</div>1460+Hello World</code></pre>1461 </div>1462 </div>1463 </body>1464 </html>deleted:docs/index.1-126 removed
1-.\" generated with Ronn/v0.7.32-.\" http://github.com/rtomayko/ronn/tree/0.7.33-.4-.TH "INDEX" "" "March 2011" "" ""5-.6-.SH "NAME"7-\fBindex\fR8-.9-.IP "" 410-.11-.nf12-13-var app = express\.createServer();14-15-app\.get(\'/\', function(req, res){16- res\.send(\'Hello World\');17-});18-19-app\.listen(3000);20-.21-.fi22-.23-.IP "" 024-.25-.SH "Features"26-.27-.IP "\(bu" 428-Robust routing29-.30-.IP "\(bu" 431-Redirection helpers32-.33-.IP "\(bu" 434-Dynamic view helpers35-.36-.IP "\(bu" 437-Application level view options38-.39-.IP "\(bu" 440-Content negotiation41-.42-.IP "\(bu" 443-Application mounting44-.45-.IP "\(bu" 446-Focus on high performance47-.48-.IP "\(bu" 449-View rendering and partials support50-.51-.IP "\(bu" 452-Environment based configuration53-.54-.IP "\(bu" 455-Session based flash notifications56-.57-.IP "\(bu" 458-Built on Connect \fIhttp://github\.com/senchalabs/connect\fR59-.60-.IP "\(bu" 461-Executable \fIexecutable\.html\fR for generating applications quickly62-.63-.IP "\(bu" 464-High test coverage65-.66-.IP "" 067-.68-.SH "Contributors"69-The following are the major contributors of Express (in no specific order)\.70-.71-.IP "\(bu" 472-TJ Holowaychuk (visionmedia \fIhttp://github\.com/visionmedia\fR)73-.74-.IP "\(bu" 475-Ciaran Jessup (ciaranj \fIhttp://github\.com/ciaranj\fR)76-.77-.IP "\(bu" 478-Aaron Heckmann (aheckmann \fIhttp://github\.com/aheckmann\fR)79-.80-.IP "\(bu" 481-Guillermo Rauch (guille \fIhttp://github\.com/guille\fR)82-.83-.IP "" 084-.85-.SH "Third\-Party Modules"86-The following modules compliment or extend Express directly:87-.88-.IP "\(bu" 489-express\-resource \fIhttp://github\.com/visionmedia/express\-resource\fR provides resourceful routing90-.91-.IP "\(bu" 492-express\-messages \fIhttp://github\.com/visionmedia/express\-messages\fR flash message notification rendering93-.94-.IP "\(bu" 495-express\-configure \fIhttp://github\.com/visionmedia/express\-configure\fR async configuration support (load settings from redis etc)96-.97-.IP "\(bu" 498-express\-namespace \fIhttp://github\.com/visionmedia/express\-namespace\fR namespaced routing support99-.100-.IP "" 0101-.102-.SH "More Information"103-.104-.IP "\(bu" 4105-Google Group \fIhttp://groups\.google\.com/group/express\-js\fR for discussion106-.107-.IP "\(bu" 4108-Follow tjholowaychuk \fIhttp://twitter\.com/tjholowaychuk\fR on twitter for updates109-.110-.IP "\(bu" 4111-View the Connect \fIhttp://senchalabs\.github\.com/connect\fR documentation112-.113-.IP "\(bu" 4114-View the Connect Wiki \fIhttp://wiki\.github\.com/senchalabs/connect/\fR for contrib middleware115-.116-.IP "\(bu" 4117-View the examples \fIhttp://github\.com/visionmedia/express/tree/master/examples/\fR118-.119-.IP "\(bu" 4120-View the source \fIhttp://github\.com/visionmedia/express\fR121-.122-.IP "\(bu" 4123-View the contrib guide \fIcontrib\.html\fR124-.125-.IP "" 0126-modified:docs/index.html+5 added-49 removed
188 unmodified lines189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193-<div class='mp'>194-<h2 id="Express">Express</h2>195-<p class="man-name">196- <code>index</code>197-</p>193 <pre><code>var app = express.createServer();194 195 app.get('/', function(req, res){196 res.send('Hello World');197 });198 204-app.listen(3000);205-</code></pre>199+app.listen(3000);</code></pre>200 201 <h2 id="Features">Features</h2>202 209-<ul>210-<li>Robust routing</li>211-<li>Redirection helpers</li>212-<li>Dynamic view helpers</li>213-<li>Application level view options</li>214-<li>Content negotiation</li>215-<li>Application mounting</li>216-<li>Focus on high performance</li>217-<li>View rendering and partials support</li>218-<li>Environment based configuration</li>219-<li>Session based flash notifications</li>220-<li>Built on <a href="http://github.com/senchalabs/connect">Connect</a></li>221-<li><a href="executable.html">Executable</a> for generating applications quickly</li>222-<li>High test coverage</li>223-</ul>203+<ul><li>Robust routing</li><li>Redirection helpers</li><li>Dynamic view helpers</li><li>Application level view options</li><li>Content negotiation</li><li>Application mounting</li><li>Focus on high performance</li><li>View rendering and partials support</li><li>Environment based configuration</li><li>Session based flash notifications</li><li>Built on <a href="http://github.com/senchalabs/connect">Connect</a></li><li><a href="executable.html">Executable</a> for generating applications quickly</li><li>High test coverage</li></ul>204 225-205 <h2 id="Contributors">Contributors</h2>206 207 <p>The following are the major contributors of Express (in no specific order).</p>208 230-<ul>231-<li>TJ Holowaychuk (<a href="http://github.com/visionmedia">visionmedia</a>)</li>232-<li>Ciaran Jessup (<a href="http://github.com/ciaranj">ciaranj</a>)</li>233-<li>Aaron Heckmann (<a href="http://github.com/aheckmann">aheckmann</a>)</li>234-<li>Guillermo Rauch (<a href="http://github.com/guille">guille</a>)</li>235-</ul>209+<ul><li>TJ Holowaychuk (<a href="http://github.com/visionmedia)">visionmedia</a></li><li>Ciaran Jessup (<a href="http://github.com/ciaranj)">ciaranj</a></li><li>Aaron Heckmann (<a href="http://github.com/aheckmann)">aheckmann</a></li><li>Guillermo Rauch (<a href="http://github.com/guille)">guille</a></li></ul>210 237-211 <h2 id="Third-Party-Modules">Third-Party Modules</h2>212 213 <p>The following modules compliment or extend Express directly:</p>214 242-<ul>243-<li><a href="http://github.com/visionmedia/express-resource">express-resource</a> provides resourceful routing</li>244-<li><a href="http://github.com/visionmedia/express-messages">express-messages</a> flash message notification rendering</li>245-<li><a href="http://github.com/visionmedia/express-configure">express-configure</a> async configuration support (load settings from redis etc)</li>246-<li><a href="http://github.com/visionmedia/express-namespace">express-namespace</a> namespaced routing support</li>247-</ul>215+<ul><li><a href="http://github.com/visionmedia/express-resource">express-resource</a> provides resourceful routing</li><li><a href="http://github.com/visionmedia/express-messages">express-messages</a> flash message notification rendering</li><li><a href="http://github.com/visionmedia/express-configure">express-configure</a> async configuration support (load settings from redis etc)</li><li><a href="http://github.com/visionmedia/express-namespace">express-namespace</a> namespaced routing support</li></ul>216 249-217 <h2 id="More-Information">More Information</h2>218 252-<ul>253-<li><a href="http://groups.google.com/group/express-js">Google Group</a> for discussion</li>254-<li>Follow <a href="http://twitter.com/tjholowaychuk">tjholowaychuk</a> on twitter for updates</li>255-<li>View the <a href="http://senchalabs.github.com/connect">Connect</a> documentation</li>256-<li>View the <a href="http://wiki.github.com/senchalabs/connect/">Connect Wiki</a> for contrib middleware</li>257-<li>View the <a href="http://github.com/visionmedia/express/tree/master/examples/">examples</a></li>258-<li>View the <a href="http://github.com/visionmedia/express">source</a></li>259-<li>View the <a href="contrib.html">contrib guide</a></li>260-</ul>261-262-263-</div>219+<ul><li><a href="http://groups.google.com/group/express-js">Google Group</a> for discussion</li><li>Follow <a href="http://twitter.com/tjholowaychuk">tjholowaychuk</a> on twitter for updates</li><li>View the <a href="http://senchalabs.github.com/connect">Connect</a> documentation</li><li>View the <a href="http://wiki.github.com/senchalabs/connect/">Connect Wiki</a> for contrib middleware</li><li>View the <a href="http://github.com/visionmedia/express/tree/master/examples/">examples</a></li><li>View the <a href="http://github.com/visionmedia/express">source</a></li><li>View the <a href="contrib.html">contrib guide</a></li></ul>220 </div>221 </div>222 </body>223 </html>deleted:docs/migrate.1-272 removed
1-.\" generated with Ronn/v0.7.32-.\" http://github.com/rtomayko/ronn/tree/0.7.33-.4-.TH "MIGRATE" "" "March 2011" "" ""5-.6-.SH "NAME"7-\fBmigrate\fR8-.9-.SS "Express 1\.x to 2\.x Migration"10-.11-.SS "HTTPS"12-Creating an HTTPS server is simply, simply pass the TLS options to \fIexpress\.createServer()\fR:13-.14-.IP "" 415-.16-.nf17-18- var app = express\.createServer({19- key: \.\.\.20- , cert: \.\.\.21- });22-23- app\.listen(443);24-.25-.fi26-.27-.IP "" 028-.29-.SS "req\.header() Referrer"30-Previously if anyone was doing something similar to:31-.32-.IP "" 433-.34-.nf35-36- req\.headers\.referrer || req\.headers\.referer37- req\.header(\'Referrer\') || req\.header(\'Referer\')38-.39-.fi40-.41-.IP "" 042-.43-.P44-With the new special\-case we may now simply use \fIReferrer\fR which will return either if defined:45-.46-.IP "" 447-.48-.nf49-50- req\.header(\'Referrer\')51-.52-.fi53-.54-.IP "" 055-.56-.SS "res\.local(name, val)"57-Previously all local variables had to be passed to \fIres\.render()\fR, or either \fIapp\.helpers()\fR or \fIapp\.dynamicHelpers()\fR, now we may do this at the request\-level progressively\. The \fIres\.local()\fR method accepts a \fIname\fR and \fIval\fR, however the locals passed to \fIres\.render()\fR will take precedence\.58-.59-.P60-For example we may utilize this feature to create locals in middleware:61-.62-.IP "" 463-.64-.nf65-66- function loadUser(req, res, next) {67- User\.get(req\.params\.id, function(err, user){68- res\.local(\'user\', user);69- next();70- });71- }72-73- app\.get(\'/user/:id\', loadUser, function(req, res){74- res\.render(\'user\');75- });76-.77-.fi78-.79-.IP "" 080-.81-.SS "req\.param(name[, defaultValue])"82-Previously only \fIname\fR was accepted, so some of you may have been doing the following:83-.84-.IP "" 485-.86-.nf87-88- var id = req\.param(\'id\') || req\.user\.id;89-.90-.fi91-.92-.IP "" 093-.94-.P95-The new \fIdefaultValue\fR argument can handle this nicely:96-.97-.IP "" 498-.99-.nf100-101- var id = req\.param(\'id\', req\.user\.id);102-.103-.fi104-.105-.IP "" 0106-.107-.SS "app\.helpers() / app\.locals()"108-\fIapp\.locals()\fR is now an alias of \fIapp\.helpers()\fR, as helpers makes more sense for functions\.109-.110-.SS "req\.accepts(type)"111-\fIreq\.accepts()\fR now accepts extensions:112-.113-.IP "" 4114-.115-.nf116-117- // Accept: text/html118- req\.accepts(\'html\');119- req\.accepts(\'\.html\');120- // => true121-122- // Accept: text/*; application/json123- req\.accepts(\'html\');124- req\.accepts(\'text/*\');125- req\.accepts(\'text/plain\');126- req\.accepts(\'application/json\');127- // => true128-129- req\.accepts(\'image/png\');130- req\.accepts(\'png\');131- // => false132-.133-.fi134-.135-.IP "" 0136-.137-.SS "res\.cookie()"138-Previously only directly values could be passed, so for example:139-.140-.IP "" 4141-.142-.nf143-144-res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000) });145-.146-.fi147-.148-.IP "" 0149-.150-.P151-However now we have the alternative \fImaxAge\fR property which may be used to set \fIexpires\fR relative to \fIDate\.now()\fR in milliseconds, so our example above can now become:152-.153-.IP "" 4154-.155-.nf156-157-res\.cookie(\'rememberme\', \'yes\', { maxAge: 900000 });158-.159-.fi160-.161-.IP "" 0162-.163-.SS "res\.download() / res\.sendfile()"164-Both of these methods now utilize Connect\'s static file server behind the scenes (actually the previous Express code was ported to Connect 1\.0)\. With this change comes a change to the callback as well\. Previously the \fIpath\fR and \fIstream\fR were passed, however now only an \fIerror\fR is passed, when no error has occurred the callback will be invoked indicating that the file transfer is complete\. The callback remains optional:165-.166-.IP "" 4167-.168-.nf169-170- res\.download(\'/path/to/file\');171-172- res\.download(\'/path/to/file\', function(err){173- if (err) {174- console\.error(err);175- } else {176- console\.log(\'transferred\');177- }178- });179-.180-.fi181-.182-.IP "" 0183-.184-.P185-The \fIstream threshold\fR setting was removed\.186-.187-.SS "res\.render()"188-Previously locals were passed as a separate key:189-.190-.IP "" 4191-.192-.nf193-194- res\.render(\'user\', { layout: false, locals: { user: user }});195-.196-.fi197-.198-.IP "" 0199-.200-.P201-In Express 2\.0 both the locals and the options are one in the same, meaning you cannot have a local variable named \fIlayout\fR as it is reserved for express, however this cleans up the API:202-.203-.IP "" 4204-.205-.nf206-207- res\.render(\'user\', { layout: false, user: user });208-.209-.fi210-.211-.IP "" 0212-.213-.SS "res\.partial()"214-Express 2\.0 adds the \fIres\.partial()\fR method, helpful for rendering partial fragments over WebSockets or Ajax requests etc\. The API is identical to the \fIpartial()\fR calls within views\.215-.216-.IP "" 4217-.218-.nf219-220- // render a collection of comments221- res\.partial(\'comment\', [comment1, comment2]);222-223- // render a single comment224- res\.partial(\'comment\', comment);225-.226-.fi227-.228-.IP "" 0229-.230-.SS "Template Engine Compliance"231-To comply with Express previously engines needed the following signature:232-.233-.IP "" 4234-.235-.nf236-237- engine\.render(str, options, function(err){});238-.239-.fi240-.241-.IP "" 0242-.243-.P244-Now they must export a \fIcompile()\fR function, returning a function which when called with local variables will render the template\. This allows Express to cache the compiled function in memory during production\.245-.246-.IP "" 4247-.248-.nf249-250- var fn = engine\.compile(str, options);251- fn(locals);252-.253-.fi254-.255-.IP "" 0256-.257-.SS "View Partial Lookup"258-Previously partials were loaded relative to the now removed \fIview partials\fR directory setting, or by default \fIviews/partials\fR, now they are relative to the view calling them, read more on view lookup \fIguide\.html#View\-Lookup\fR\.259-.260-.SS "Mime Types"261-Express and Connect now utilize the \fImime\fR module in npm, so to add more use:262-.263-.IP "" 4264-.265-.nf266-267- require(\'mime\')\.define({ \'foo/bar\': [\'foo\', \'bar\'] });268-.269-.fi270-.271-.IP "" 0272-modified:docs/migrate.html+57 added-46 removed
188 unmodified lines189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193-<div class='mp'>194-<h2 id="Express">Express</h2>195-<p class="man-name">196- <code>migrate</code>197-</p>193 <h3 id="Express-1-x-to-2-x-Migration">Express 1.x to 2.x Migration</h3>194 195 <h3 id="HTTPS">HTTPS</h3>196 3 unmodified lines200 key: ...201 , cert: ...202 });203 209- app.listen(443);210-</code></pre>204+ app.listen(443);</code></pre>205 206 <h3 id="req-header-Referrer">req.header() Referrer</h3>207 208 <p> Previously if anyone was doing something similar to:</p>209 210 <pre><code> req.headers.referrer || req.headers.referer217- req.header('Referrer') || req.header('Referer')218-</code></pre>211+ req.header('Referrer') || req.header('Referer')</code></pre>212 213 <p> With the new special-case we may now simply use <em>Referrer</em> which will return either if defined:</p>214 222-<pre><code> req.header('Referrer')223-</code></pre>215+<pre><code> req.header('Referrer')</code></pre>216 225-<h3 id="res-local-name-val-">res.local(name, val)</h3>217+<h3 id="res-local-name-val">res.local(name, val)</h3>218 219 <p> Previously all local variables had to be passed to <em>res.render()</em>, or either <em>app.helpers()</em> or <em>app.dynamicHelpers()</em>, now we may do this at the request-level progressively. The <em>res.local()</em> method accepts a <em>name</em> and <em>val</em>, however the locals passed to <em>res.render()</em> will take precedence.</p>220 221 <p> For example we may utilize this feature to create locals in middleware:</p>6 unmodified lines228 }229 230 app.get('/user/:id', loadUser, function(req, res){231 res.render('user');240- });241-</code></pre>232+ });</code></pre>233 243-<h3 id="req-param-name-defaultValue-">req.param(name[, defaultValue])</h3>234+<h3 id="req-param-name-defaultValue">req.param(name[, defaultValue])</h3>235 236 <p> Previously only <em>name</em> was accepted, so some of you may have been doing the following:</p>237 247-<pre><code> var id = req.param('id') || req.user.id;248-</code></pre>238+<pre><code> var id = req.param('id') || req.user.id;</code></pre>239 240 <p> The new <em>defaultValue</em> argument can handle this nicely:</p>241 252-<pre><code> var id = req.param('id', req.user.id);253-</code></pre>242+<pre><code> var id = req.param('id', req.user.id);</code></pre>243 255-<h3 id="app-helpers-app-locals-">app.helpers() / app.locals()</h3>244+<h3 id="app-helpers-app-locals">app.helpers() / app.locals()</h3>245 246 <p> <em>app.locals()</em> is now an alias of <em>app.helpers()</em>, as helpers makes more sense for functions.</p>247 259-<h3 id="req-accepts-type-">req.accepts(type)</h3>248+<h3 id="req-accepts-type">req.accepts(type)</h3>249 250 <p> <em>req.accepts()</em> now accepts extensions:</p>251 252 <pre><code> // Accept: text/html9 unmodified lines262 // => true263 264 req.accepts('image/png');265 req.accepts('png');277- // => false278-</code></pre>266+ // => false</code></pre>267 280-<h3 id="res-cookie-">res.cookie()</h3>268+<h3 id="res-cookie">res.cookie()</h3>269 270 <p> Previously only directly values could be passed, so for example:</p>271 284-<pre><code>res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000) });285-</code></pre>272+<pre><code>res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000) });</code></pre>273 274 <p>However now we have the alternative <em>maxAge</em> property which may be used to set <em>expires</em> relative to <em>Date.now()</em> in milliseconds, so our example above can now become:</p>275 289-<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });290-</code></pre>276+<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });</code></pre>277 292-<h3 id="res-download-res-sendfile-">res.download() / res.sendfile()</h3>278+<h3 id="res-download-res-sendfile">res.download() / res.sendfile()</h3>279 280 <p> Both of these methods now utilize Connect's static file server behind the scenes (actually the previous Express code was ported to Connect 1.0). With this change comes a change to the callback as well. Previously the <em>path</em> and <em>stream</em> were passed, however now only an <em>error</em> is passed, when no error has occurred the callback will be invoked indicating that the file transfer is complete. The callback remains optional:</p>281 282 <pre><code> res.download('/path/to/file');3 unmodified lines286 console.error(err);287 } else {288 console.log('transferred');289 }304- });305-</code></pre>290+ });</code></pre>291 292 <p> The <em>stream threshold</em> setting was removed.</p>293 309-<h3 id="res-render-">res.render()</h3>294+<h3 id="res-render">res.render()</h3>295 296 <p> Previously locals were passed as a separate key:</p>297 313-<pre><code> res.render('user', { layout: false, locals: { user: user }});314-</code></pre>298+<pre><code> res.render('user', { layout: false, locals: { user: user }});</code></pre>299 300 <p> In Express 2.0 both the locals and the options are one in the same, meaning you cannot have a local variable named <em>layout</em> as it is reserved for express, however this cleans up the API:</p>301 318-<pre><code> res.render('user', { layout: false, user: user });319-</code></pre>302+<pre><code> res.render('user', { layout: false, user: user });</code></pre>303 321-<h3 id="res-partial-">res.partial()</h3>304+<h3 id="res-partial">res.partial()</h3>305 306 <p> Express 2.0 adds the <em>res.partial()</em> method, helpful for rendering partial fragments over WebSockets or Ajax requests etc. The API is identical to the <em>partial()</em> calls within views.</p>307 308 <pre><code> // render a collection of comments309 res.partial('comment', [comment1, comment2]); 310 311 // render a single comment329- res.partial('comment', comment);330-</code></pre>312+ res.partial('comment', comment);</code></pre>313 314+<h3 id="partial-locals">partial() locals</h3>315+316+<p> Both <em>res.partial()</em> and the <em>partial()</em> functions accept an single object consisting of both the options and the locals. Previously with Express 1.x you may pass <em>user</em> to a partial, along with <em>date</em> like so:</p>317+318+<pre><code> partial('user', { object: user, locals: { date: new Date }})</code></pre>319+320+<p>or perhaps if you preferred not to use the inferred name <em>user</em> you may used a local for this as well:</p>321+322+<pre><code> partial('user', { locals: { user: user, date: new Date }})</code></pre>323+324+<p> With recent changes to Express 2.x the object passed is now both, so the following is valid for the <em>object</em> option and locals:</p>325+326+<pre><code> partial('user', { object: user, date: new Date })</code></pre>327+328+<p> Or the following which is equivalent, however the local var name is explicitly set to <em>user</em> instead of deduced from the filename.</p>329+330+<pre><code> partial('user', { user: user, date: new Date })</code></pre>331+332+<p> When a "basic" object aka <em>{}</em> or <em>new Object</em> is passed, it is considered options, otherwise it is considered the <em>object</em>. The following are equivalent:</p>333+334+<pre><code> partial('user', user); 335+ partial('user', { object: user }); </code></pre>336+337 <h3 id="Template-Engine-Compliance">Template Engine Compliance</h3>338 339 <p> To comply with Express previously engines needed the following signature:</p>340 336-<pre><code> engine.render(str, options, function(err){});337-</code></pre>341+<pre><code> engine.render(str, options, function(err){});</code></pre>342 343 <p> Now they must export a <em>compile()</em> function, returning a function which when called with local variables will render the template. This allows Express to cache the compiled function in memory during production.</p>344 345 <pre><code> var fn = engine.compile(str, options);342- fn(locals);343-</code></pre>346+ fn(locals);</code></pre>347 348 <h3 id="View-Partial-Lookup">View Partial Lookup</h3>349 350 <p> Previously partials were loaded relative to the now removed <em>view partials</em> directory setting, or by default <em>views/partials</em>, now they are relative to the view calling them, read more on <a href="guide.html#View-Lookup">view lookup</a>.</p>1 unmodified line352 <h3 id="Mime-Types">Mime Types</h3>353 354 <p> Express and Connect now utilize the <em>mime</em> module in npm, so to add more use:</p>355 353-<pre><code> require('mime').define({ 'foo/bar': ['foo', 'bar'] });354-</code></pre>356+<pre><code> require('mime').define({ 'foo/bar': ['foo', 'bar'] });</code></pre>357 356-</div>358+<h3 id="static-middleware">static() middleware</h3>359+360+<p> Previously named <code>staticProvider()</code>, the now <code>static()</code> middleware takes a single directory path, followed by options.</p>361+362+<pre><code> app.use(express.static(__dirname + '/public', { maxAge: oneYear }));</code></pre>363+364+<p>Previously when using options the <code>root</code> option would be used for this:</p>365+366+<pre><code> app.use(express.staticProvider({ root: __dirname + '/public', maxAge: oneYear }));367+ </code></pre>368 </div>369 </div>370 </body>371 </html>deleted:docs/screencasts.1-28 removed
1-.\" generated with Ronn/v0.7.32-.\" http://github.com/rtomayko/ronn/tree/0.7.33-.4-.TH "SCREENCASTS" "" "March 2011" "" ""5-.6-.SH "NAME"7-\fBscreencasts\fR8-.9-.SS "Introduction"10-This introduction screencast covers the basics of Express, and how to get started with your first application\.11-.12-.P13-.14-.SS "View Partials"15-In this screencast we work with partials to display a collection of users using the Jade \fIhttp://jade\-lang\.com\fR template engine, and learn about view path resolution\.16-.17-.P18-.19-.SS "Route Specific Middleware"20-In the screencast below we learn about the benefits of route\-specific middleware\.21-.22-.P23-.24-.SS "Route Param Preconditions"25-Learn about route parameter (\fI/user/:id\fR) pre\-conditions, providing automated validation, and loading of data via the named route param segments\.26-.27-.P28-modified:docs/screencasts.html+4 added-11 removed
188 unmodified lines189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193-<div class='mp'>194-<h2 id="Express">Express</h2>195-<p class="man-name">196- <code>screencasts</code>197-</p>193 <h3 id="Introduction">Introduction</h3>194 195 <p>This introduction screencast covers the basics of Express, and how to get started with your first application.</p>196 202-<p><object height="345" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0"><param name="movie" value="http://screenr.com/Content/assets/screenr_1116090935.swf" /><param name="flashvars" value="i=139583" /><param name="allowFullScreen" value="true" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" src="http://screenr.com/Content/assets/screenr_1116090935.swf" height="345" flashvars="i=139583" width="560"></embed></object></p>197+<p><object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0' width='560' height='345'><param name='movie' value='http://screenr.com/Content/assets/screenr<em>1116090935.swf' /><param name='flashvars' value='i=139583' /><param name='allowFullScreen' value='true' /><embed src='http://screenr.com/Content/assets/screenr</em>1116090935.swf' flashvars='i=139583' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></object></p>198 199 <h3 id="View-Partials">View Partials</h3>200 201 <p>In this screencast we work with partials to display a collection of users using the <a href="http://jade-lang.com">Jade</a> template engine, and learn about view path resolution.</p>202 208-<p><object height="345" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0"><param name="movie" value="http://screenr.com/Content/assets/screenr_1116090935.swf" /><param name="flashvars" value="i=139591" /><param name="allowFullScreen" value="true" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" src="http://screenr.com/Content/assets/screenr_1116090935.swf" height="345" flashvars="i=139591" width="560"></embed></object></p>203+<p><object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0' width='560' height='345'><param name='movie' value='http://screenr.com/Content/assets/screenr<em>1116090935.swf' /><param name='flashvars' value='i=139591' /><param name='allowFullScreen' value='true' /><embed src='http://screenr.com/Content/assets/screenr</em>1116090935.swf' flashvars='i=139591' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></object></p>204 205 <h3 id="Route-Specific-Middleware">Route Specific Middleware</h3>206 207 <p>In the screencast below we learn about the benefits of route-specific middleware.</p>208 214-<p><object height="345" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0"><param name="movie" value="http://screenr.com/Content/assets/screenr_1116090935.swf" /><param name="flashvars" value="i=140296" /><param name="allowFullScreen" value="true" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" src="http://screenr.com/Content/assets/screenr_1116090935.swf" height="345" flashvars="i=140296" width="560"></embed></object></p>209+<p><object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0' width='560' height='345'><param name='movie' value='http://screenr.com/Content/assets/screenr<em>1116090935.swf' /><param name='flashvars' value='i=140296' /><param name='allowFullScreen' value='true' /><embed src='http://screenr.com/Content/assets/screenr</em>1116090935.swf' flashvars='i=140296' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></object></p>210 211 <h3 id="Route-Param-Preconditions">Route Param Preconditions</h3>212 213 <p>Learn about route parameter (<em>/user/:id</em>) pre-conditions, providing automated validation, and loading of data via the named route param segments.</p>214 220-<p><object height="345" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0"><param name="movie" value="http://screenr.com/Content/assets/screenr_1116090935.swf" /><param name="flashvars" value="i=140300" /><param name="allowFullScreen" value="true" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" src="http://screenr.com/Content/assets/screenr_1116090935.swf" height="345" flashvars="i=140300" width="560"></embed></object></p>221-222-</div>215+<p><object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0' width='560' height='345'><param name='movie' value='http://screenr.com/Content/assets/screenr<em>1116090935.swf' /><param name='flashvars' value='i=140300' /><param name='allowFullScreen' value='true' /><embed src='http://screenr.com/Content/assets/screenr</em>1116090935.swf' flashvars='i=140300' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></object></p>216 </div>217 </div>218 </body>219 </html>modified:Makefile+1 added-1 removed
20 unmodified lines21 @./support/toc.js docs/guide.html22 23 %.html: %.md24 @echo "... $< -> $@"25- @ronn -5 --pipe --fragment $< \25+ @ronn --fragment $< \26 | cat docs/layout/head.html - docs/layout/foot.html \27 | sed 's/NAME/Express/g' \28 > $@29 11 unmodified lines