Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,083 lines · 34.0 KiB · HTML

Last changed by

Updated docsTj Holowaychukbefore adoptionf0eab06

History of this file

Take it

1<html>2	<head>3		<title>Express - node web framework</title>4		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>5		<style>6			#tagline {7			  margin-left: 75px;8			  margin-bottom: 30px;9			  color: rgba(255,255,255,0.7); }10			html {11			  background: #1c1c1c url(images/bg.tile.jpg); }1213			body {14			  margin: 0;15			  padding-bottom: 30px;16			  font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";17			  font-size: 14px;18			  line-height: 1.5;19			  -webkit-text-stroke: 1px rgba(0, 0, 0, 0.1);20			  -moz-text-stroke: 1px rgba(0, 0, 0, 0.1);21			  background: url(images/bg.jpg) 50% 0 no-repeat;22			  color: #8b8b8b; }2324			* {25			  outline: none; }2627			em {28			  color: white; }2930			a img {31			  border: none !important; }3233			a {34			  font-weight: bold;35			  text-decoration: none;36			  color: white;37			  -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;38			  -webkit-transition-duration: 0.15s;39			  -webkit-transition-timing-function: ease-out; }40			  a:hover {41			    opacity: 0.8; }4243			h1, h2, h3 {44			  margin: 45px 0 0 0;45			  color: white;46			  text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4748			h3 {49			  font-size: 18px; }5051			pre {52			  margin: 20px 10px;53			  padding: 25px 20px;54			  background: rgba(0,0,0,0.5);55			  border: 1px solid #323232;56			  -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);57			  -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);58			  -webkit-border-radius: 5px;59			  -moz-border-radius: 5px; }6061			code {62			  font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6364			ul {65			  margin: 15px 0;66			  padding: 0 0 0 35px; }67			  ul li {68			    margin: 0;69			    padding: 2px 0;70			    list-style: square; }71          ul li ul {72            margin: 0;73            padding-left: 12px;74          }7576      .man-name, #Express { display:none; }7778			.sect {79			  margin-left: 40px; }8081			#logo {82			  display: block;83			  margin-left: 30%;84			  margin-bottom: 30px;85			  width: 194px;86			  height: 51px;87			  background: url(images/logo.png) 0 0 no-repeat;88			  text-indent: -99999px; }89			  #logo:hover {90			    opacity: 0.7; }91			  #logo:active {92			    opacity: 0.3; }9394			#ribbon {95			  position: fixed;96			  top: 0;97			  right: 0;98			  z-index: 2; }99100			#wrapper {101			  width: 100%;102			  min-height: 800px;103			  background: url(images/top.png) 0 0 repeat-x; }104105			#container {106			  margin: 0 auto;107			  padding-top: 80px;108			  width: 550px; }109110			#toc {111				position: fixed;112				top: 0;113				left: 0;114				margin: 0 0 0 15px;115				padding: 15px;116				height: 100%;117				background: rgba(0,0,0,0.2);118				overflow: auto;119				border-right: 1px solid rgba(255,255,255,0.05);120			}121			#toc li {122				padding: 0;123				list-style: none;124			}125			#toc li a {126				font-size: 11px;127			}128			#menu {129			  margin-left: 65px;130			  padding: 0;131			  padding-bottom: 30px; }132			  #menu li {133			    display: inline;134			    list-style: none; }135			    #menu li a {136			      display: block;137			      float: left;138			      margin: 0 2px;139			      padding: 3px 15px;140			      background: rgba(0,0,0,0.2);141			      -webkit-border-radius: 8px;142			      -moz-border-radius: 8px;143			      -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);144			      -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);145			      -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;146			      -webkit-transition-duration: 0.15s;147			      -webkit-transition-timing-function: ease-out; }148			      #menu li a:hover,149			      #menu li a.active {150			        background: rgba(0,0,0,0.5); }151			      #menu li a:active {152			        background: rgba(0,0,0,0.1);153			        -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);154			        -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }155		</style>156		<script>157		  $(function(){158		    $('.section').hide();159		    $('.toggle, a.section-title').toggle(function(){160		      $(this).siblings('ul').fadeIn(300);161		      return false;162		    }, function(){163		      $(this).siblings('ul').fadeOut(300);164		      return false;165		    });166		  });167		</script>168	</head>169	<body>170		<a href='http://github.com/visionmedia/express'> 171		  <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 172		</a>173		<div id="wrapper">174			<div id="container"><ul id="toc">175<li><a href="#Installation">Installation</a></li>176<li><a href="#Creating-An-Application">Creating An Application</a></li>177<li><a href="#Configuration">Configuration</a></li>178<li><a href="#Settings">Settings</a></li>179<li><a href="#Routing">Routing</a></li>180<li><a href="#Passing-Route-Control">Passing Route Control</a></li>181<li><a href="#Middleware">Middleware</a></li>182<li><a href="#Error-Handling">Error Handling</a></li>183<li><a href="#View-Rendering">View Rendering</a></li>184<li><a href="#View-Partials">View Partials</a></li>185<li><a href="#Template-Engines">Template Engines</a></li>186<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">187<li><a href="#req-header-key-defaultValue-">header()</a></li>188<li><a href="#req-accepts-type-">accepts()</a></li>189<li><a href="#req-param-name-">param()</a></li>190<li><a href="#req-flash-type-msg-">flash()</a></li>191<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>192</ul></li>193<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">194<li><a href="#res-header-key-val-">header()</a></li>195<li><a href="#res-contentType-type-">contentType()</a></li>196<li><a href="#res-attachment-filename-">attachment()</a></li>197<li><a href="#res-sendfile-path-">sendfile()</a></li>198<li><a href="#res-download-file-filename-">download()</a></li>199<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>200<li><a href="#res-redirect-url-status-">redirect()</a></li>201<li><a href="#res-cookie-name-val-options-">cookie()</a></li>202<li><a href="#res-clearCookie-name-">clearCookie()</a></li>203<li><a href="#res-render-view-options-fn-">render()</a></li>204<li><a href="#res-partial-view-options-">partial()</a></li>205</ul></li>206<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">207<li><a href="#app-set-name-val-">set()</a></li>208<li><a href="#app-enable-name-">enable()</a></li>209<li><a href="#app-disable-name-">disable()</a></li>210<li><a href="#app-configure-env-function-function-">configure()</a></li>211<li><a href="#app-redirect-name-val-">redirect()</a></li>212<li><a href="#app-error-function-">error()</a></li>213<li><a href="#app-helpers-obj-">helpers()</a></li>214<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>215<li><a href="#app-mounted-fn-">mounted()</a></li>216<li><a href="#app-register-ext-exports-">register()</a></li>217<li><a href="#app-listen-port-host-">listen()</a></li>218</ul></li>219</ul>220				<a href='http://github.com/visionmedia/express' id='logo'>Express</a> 221				<p id="tagline">222				   High performance, high class web development for223				  <a href="http://nodejs.org">Node.js</a>224				</p>225				<ul id="menu">226					<li><a href="index.html">Home</a></li>227					<li><a href="guide.html">Guide</a></li>228					<li><a href="contrib.html">Contributing</a></li>229					<li><a href="migrate.html">1.x Migration</a></li>230				</ul>231<div class='mp'>232<h2 id="Express">Express</h2>233<p class="man-name">234  <code>guide</code>235</p>236<h3 id="Installation">Installation</h3>237238<p>curl:</p>239240<pre><code>$ curl -# http://expressjs.com/install.sh | sh241</code></pre>242243<p>npm:</p>244245<pre><code>$ npm install express246</code></pre>247248<p>git clone, first update the submodules:</p>249250<pre><code>$ git submodule update --init251$ make install252$ make install-support253</code></pre>254255<h3 id="Creating-An-Application">Creating An Application</h3>256257<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however258follows the same idiom by providing <em>express.createServer()</em> as shown below. This means259that you can utilize Express server's transparently with other libraries.</p>260261<pre><code>var app = require('express').createServer();262263app.get('/', function(req, res){264    res.send('hello world');265});266267app.listen(3000);268</code></pre>269270<h3 id="Configuration">Configuration</h3>271272<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers273can use the <em>configure()</em> method to setup needs required by the current environment. When274<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment275prior to the environment specific callback.</p>276277<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces278in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.279Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,280otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>281282<pre><code>app.configure(function(){283    app.use(express.methodOverride());284    app.use(express.bodyDecoder());285    app.use(app.router);286    app.use(express.staticProvider(__dirname + '/public'));287});288289app.configure('development', function(){290    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));291});292293app.configure('production', function(){294    app.use(express.errorHandler());295});296</code></pre>297298<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>299300<pre><code>app.configure(function(){301    app.set('views', __dirname + '/views');302    app.set('views');303    // =&gt; "... views directory ..."304305    app.enable('some feature');306    // same as app.set('some feature', true);307308    app.disable('some feature');309    // same as app.set('some feature', false);310});311</code></pre>312313<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,314or more specifically <em>EXPRESS_ENV</em>, for example:</p>315316<pre><code>$ EXPRESS_ENV=production node app.js317</code></pre>318319<h3 id="Settings">Settings</h3>320321<p>Express supports the following settings out of the box:</p>322323<ul>324<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>325<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>326<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>327<li><em>view engine</em> Default view engine name for views rendered without extensions</li>328<li><em>view options</em> An object specifying global view options</li>329<li><em>partials</em> Root view partials directory defaulting to <em>views</em>/partials.</li>330<li><em>stream threshold</em> Bytesize indicating when a file should be streamed for <em>res.sendfile()</em> using <em>fs.ReadStream()</em> and <em>sys.pump()</em>.</li>331</ul>332333334<h3 id="Routing">Routing</h3>335336<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.337For example we may want to render a user's account for the path <em>/user/12</em>, this338can be done by defining the route below. The values associated to the named placeholders339are available as <code>req.params</code>.</p>340341<pre><code>app.get('/user/:id', function(req, res){342    res.send('user ' + req.params.id);343});344</code></pre>345346<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example347when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>348349<pre><code>\/user\/([^\/]+)\/?350</code></pre>351352<p>Regular expression literals may also be passed for complex uses. Since capture353groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>.</p>354355<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){356    res.send(req.params);357});358</code></pre>359360<p>Curl requests against the previously defined route:</p>361362<pre><code>   $ curl http://dev:3000/user363   [null,null]364   $ curl http://dev:3000/users365   [null,null]366   $ curl http://dev:3000/users/1367   ["1",null]368   $ curl http://dev:3000/users/1..15369   ["1","15"]370</code></pre>371372<p>Below are some route examples, and the associated paths that they373may consume:</p>374375<pre><code> "/user/:id"376 /user/12377378 "/users/:id?"379 /users/5380 /users381382 "/files/*"383 /files/jquery.js384 /files/javascripts/jquery.js385386 "/file/*.*"387 /files/jquery.js388 /files/javascripts/jquery.js389390 "/user/:id/:operation?"391 /user/1392 /user/1/edit393394 "/products.:format"395 /products.json396 /products.xml397398 "/products.:format?"399 /products.json400 /products.xml401 /products402</code></pre>403404<h3 id="Passing-Route-Control">Passing Route Control</h3>405406<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,407the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,408and middleware continue to be invoked.</p>409410<pre><code>app.get('/users/:id?', function(req, res, next){411    var id = req.params.id;412    if (id) {413        // do something414    } else {415        next();416    }417});418419app.get('/users', function(req, res){420    // do something else421});422</code></pre>423424<h3 id="Middleware">Middleware</h3>425426<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be427passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>428429<pre><code>var express = require('express');430431var app = express.createServer(432    express.logger(),433    express.bodyDecoder()434);435</code></pre>436437<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>438439<pre><code>app.use(express.logger({ format: ':method :uri' }));440</code></pre>441442<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>443444<pre><code>var connect = require('connect');445app.use(connect.logger());446</code></pre>447448<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>449450<pre><code>app.use(express.logger());451</code></pre>452453<h3 id="Error-Handling">Error Handling</h3>454455<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,456or passed to <em>next(err)</em>. Below is an example which serves different pages based on our457ad-hoc <em>NotFound</em> exception:</p>458459<pre><code>function NotFound(msg){460    this.name = 'NotFound';461    Error.call(this, msg);462    Error.captureStackTrace(this, arguments.callee);463}464465sys.inherits(NotFound, Error);466467app.get('/404', function(req, res){468    throw new NotFound;469});470471app.get('/500', function(req, res){472    throw new Error('keyboard cat!');473});474</code></pre>475476<p>We can call <em>app.error()</em> several times as shown below.477Here we check for an instanceof <em>NotFound</em> and show the478404 page, or we pass on to the next error handler.</p>479480<p>Note that these handlers can be defined anywhere, as they481will be placed below the route handlers on <em>listen()</em>. This482allows for definition within <em>configure()</em> blocks so we can483handle exceptions in different ways based on the environment.</p>484485<pre><code>app.error(function(err, req, res, next){486    if (err instanceof NotFound) {487        res.render('404.jade');488    } else {489        next(err);490    }491});492</code></pre>493494<p>Here we assume all errors as 500 for the simplicity of495this demo, however you can choose whatever you like</p>496497<pre><code>app.error(function(err, req, res){498    res.render('500.jade', {499       locals: {500           error: err501       } 502    });503});504</code></pre>505506<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware507to report on exceptions. For example if we wish to output exceptions508in "development" mode to <em>stderr</em> we can use:</p>509510<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));511</code></pre>512513<p>Also during development we may want fancy html pages to show exceptions514that are passed or thrown, so we can set <em>showStack</em> to true:</p>515516<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));517</code></pre>518519<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>520is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>521522<h3 id="View-Rendering">View Rendering</h3>523524<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name525of the module that will be required. For example the view <em>layout.ejs</em> will526tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.render(str, options)</em> to comply with Express, however527<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.</p>528529<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,530and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as531the <em>body</em> local variable in <em>layout.haml</em>.</p>532533<pre><code>app.get('/', function(req, res){534    res.render('index.haml', {535        locals: { title: 'My Site' }536    });537});538</code></pre>539540<p>The new <em>view engine</em> setting allows us to specify our default template engine,541so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>542543<pre><code>app.set('view engine', 'jade');544</code></pre>545546<p>Allowing us to render with:</p>547548<pre><code>res.render('index');549</code></pre>550551<p>vs:</p>552553<pre><code>res.render('index.jade');554</code></pre>555556<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still557mix and match template engines:</p>558559<pre><code>res.render('another-page.ejs');560</code></pre>561562<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>563564<pre><code>app.set('view options', {565    layout: false566});567</code></pre>568569<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>570571<pre><code>res.render('myview.ejs', { layout: true });572</code></pre>573574<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>575576<pre><code>app.set('view options', {577    open: '{{',578    close: '}}'579});580</code></pre>581582<h3 id="View-Partials">View Partials</h3>583584<p>The Express view system has built-in support for partials and collections, which are585sort of "mini" views representing a document fragment. For example rather than iterating586in a view to display comments, we would use a partial with collection support:</p>587588<pre><code>partial('comment.haml', { collection: comments });589</code></pre>590591<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,592however if we wished we could use an ejs partial, within a haml view for example.</p>593594<pre><code>partial('comment', { collection: comments });595</code></pre>596597<p>And once again even further, when rendering a collection we can simply pass598an array, if no other options are desired:</p>599600<pre><code>partial('comments', comments);601</code></pre>602603<p>When using the partial collection support a few "magic" variables are provided604for free:</p>605606<ul>607<li><em>firstInCollection</em>  True if this is the first object</li>608<li><em>indexInCollection</em>  Index of the object in the collection</li>609<li><em>lastInCollection</em>  True if this is the last object</li>610</ul>611612613<h3 id="Template-Engines">Template Engines</h3>614615<p>Below are a few template engines commonly used with Express:</p>616617<ul>618<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>619<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>620<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>621</ul>622623624<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>625626<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>627628<pre><code>req.header('Host');629req.header('host');630req.header('Accept', '*/*');631</code></pre>632633<h3 id="req-accepts-type-">req.accepts(type)</h3>634635<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>636637<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise638the given <em>type</em> is matched by an exact match, and then subtypes. You639may pass the subtype such as "html" which is then converted internally640to "text/html" using the mime lookup table.</p>641642<pre><code>// Accept: text/html643req.accepts('html');644// =&gt; true645646// Accept: text/*; application/json647req.accepts('html');648req.accepts('text/html');649req.accepts('text/plain');650req.accepts('application/json');651// =&gt; true652653req.accepts('image/png');654req.accepts('png');655// =&gt; false656</code></pre>657658<h3 id="req-param-name-">req.param(name)</h3>659660<p>Return the value of param <em>name</em> when present.</p>661662<ul>663<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>664<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>665<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>666</ul>667668669<p>To utilize urlencoded request bodies, <em>req.body</em>670should be an object. This can be done by using671the <em>express.bodyDecoder</em> middleware.</p>672673<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>674675<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>676677<pre><code>req.flash('info', 'email sent');678req.flash('error', 'email delivery failed');679req.flash('info', 'email re-sent');680// =&gt; 2681682req.flash('info');683// =&gt; ['email sent', 'email re-sent']684685req.flash('info');686// =&gt; []687688req.flash();689// =&gt; { error: ['email delivery failed'], info: [] }690</code></pre>691692<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>693694<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);695</code></pre>696697<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>698699<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header700to see if it was issued by an <em>XMLHttpRequest</em>:</p>701702<pre><code>req.xhr703req.isXMLHttpRequest704</code></pre>705706<h3 id="res-header-key-val-">res.header(key[, val])</h3>707708<p>Get or set the response header <em>key</em>.</p>709710<pre><code>res.header('Content-Length');711// =&gt; undefined712713res.header('Content-Length', 123);714// =&gt; 123715716res.header('Content-Length');717// =&gt; 123718</code></pre>719720<h3 id="res-contentType-type-">res.contentType(type)</h3>721722<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>723724<pre><code>  var filename = 'path/to/image.png';725  res.contentType(filename);726  // res.headers['Content-Type'] is now "image/png"727</code></pre>728729<h3 id="res-attachment-filename-">res.attachment([filename])</h3>730731<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>732733<pre><code>  res.attachment('path/to/my/image.png');734</code></pre>735736<h3 id="res-sendfile-path-">res.sendfile(path)</h3>737738<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>739740<pre><code>res.sendfile('path/to/my.file');741</code></pre>742743<p>This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has <strong>not</strong> been streamed, <em>next(err)</em> will be called on an exception.</p>744745<pre><code>res.sendfile(path, function(err, path){746  if (err) {747    // handle the error748  } else {749    console.log('transferred %s', path);750  }751});752</code></pre>753754<p>When the filesize exceeds the <em>stream threshold</em> (defaulting to 32k), the file will be streamed using <em>fs.ReadStream</em> and <em>sys.pump()</em>.</p>755756<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>757758<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>759760<pre><code>res.download('path/to/image.png');761res.download('path/to/image.png', 'foo.png');762</code></pre>763764<p>This is equivalent to:</p>765766<pre><code>res.attachment(file);767res.sendfile(file);768</code></pre>769770<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>771772<p>The <code>res.send()</code> method is a high level response utility allowing you to pass773objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status774code based responses. The following are all valid uses:</p>775776<pre><code> res.send(); // 204777 res.send(new Buffer('wahoo'));778 res.send({ some: 'json' });779 res.send('&lt;p&gt;some html&lt;/p&gt;');780 res.send('Sorry, cant find that', 404);781 res.send('text', { 'Content-Type': 'text/plain' }, 201);782 res.send(404);783</code></pre>784785<p>By default the <em>Content-Type</em> response header is set, however if explicitly786assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>787it will not be set again.</p>788789<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>790791<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>792793<pre><code>res.redirect('/', 301);794res.redirect('/account');795res.redirect('http://google.com');796res.redirect('home');797res.redirect('back');798</code></pre>799800<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.801The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes802the "home" setting and defaults to "/".</p>803804<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>805806<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>807808<pre><code>// "Remember me" for 15 minutes 809res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });810</code></pre>811812<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>813814<pre><code>app.use(express.cookieDecoder());815816app.get('/', function(req, res){817    // use req.cookies.rememberme818});819</code></pre>820821<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>822823<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>824825<pre><code>res.clearCookie('rememberme');826</code></pre>827828<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>829830<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.831When a callback function is given a response will <em>not</em> be made832automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>833834<p> Most engines accept one or more of the following options,835 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>836837<ul>838<li><em>context|scope</em>   Template evaluation context (<em>this</em>)</li>839<li><em>locals</em>          Object containing local variables</li>840<li><em>debug</em>           Output debugging information</li>841<li><em>status</em>          Response status code, defaults to 200</li>842<li><em>headers</em>         Response headers object</li>843</ul>844845846<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>847848<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available849to the view as a local variable.</p>850851<ul>852<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>853854<ul>855<li>as: 'something' will add the <em>something</em> local variable</li>856<li>as: this will use the collection value as the template context</li>857<li>as: global will merge the collection value's properties with <em>locals</em></li>858</ul>859</li>860<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.861For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>862</ul>863864865<p>The following are equivalent, and the name of collection value when passed866to the partial will be <em>movie</em> as derived from the name.</p>867868<pre><code>partial('movie.jade', { collection: movies });869partial('movie.jade', movies);870partial('movie', movies);871// In view: movie.director872</code></pre>873874<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>875876<pre><code>partial('movie', { collection: movies, as: 'video' });877// In view: video.director878</code></pre>879880<p>Also we can make our movie the value of <em>this</em> within our view so that instead881of <em>movie.director</em> we could use <em>this.director</em>.</p>882883<pre><code>partial('movie', { collection: movies, as: this });884// In view: this.director885</code></pre>886887<p>Another alternative is to "explode" the properties of the collection item into888pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>889890<pre><code>partials('movie', { collection: movies, as: global });891// In view: director892</code></pre>893894<h3 id="app-set-name-val-">app.set(name[, val])</h3>895896<p>Apply an application level setting <em>name</em> to <em>val</em>, or897get the value of <em>name</em> when <em>val</em> is not present:</p>898899<pre><code>app.set('views', __dirname + '/views');900app.set('views');901// =&gt; ...path...902</code></pre>903904<h3 id="app-enable-name-">app.enable(name)</h3>905906<p>Enable the given setting <em>name</em>:</p>907908<pre><code>app.enable('some arbitrary setting');909app.set('some arbitrary setting');910// =&gt; true911</code></pre>912913<h3 id="app-disable-name-">app.disable(name)</h3>914915<p>Disable the given setting <em>name</em>:</p>916917<pre><code>app.disable('some setting');918app.set('some setting');919// =&gt; false920</code></pre>921922<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>923924<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>925926<pre><code>app.configure(function(){927    // executed for each env928});929930app.configure('development', function(){931    // executed for 'development' only932});933</code></pre>934935<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>936937<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>938939<pre><code>app.redirect('google', 'http://google.com');940</code></pre>941942<p>Now in a route we may call:</p>943944<p>   res.redirect('google');</p>945946<p>We may also map dynamic redirects:</p>947948<pre><code>app.redirect('comments', function(req, res){949    return '/post/' + req.params.id + '/comments';950});951</code></pre>952953<p>So now we may do the following, and the redirect will dynamically adjust to954the context of the request. If we called this route with <em>GET /post/12</em> our955redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>956957<pre><code>app.get('/post/:id', function(req, res){958    res.redirect('comments');959});960</code></pre>961962<h3 id="app-error-function-">app.error(function)</h3>963964<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.965Note that we may set several error handlers by making several calls to this method, however the handler966should call <em>next(err)</em> if it does not wish to deal with the exception:</p>967968<pre><code>app.error(function(err, req, res, next){969    res.send(err.message, 500);970});971</code></pre>972973<h3 id="app-helpers-obj-">app.helpers(obj)</h3>974975<p>Registers static view helpers.</p>976977<pre><code>app.helpers({978    name: function(first, last){ return first + ', ' + last },979    firstName: 'tj',980    lastName: 'holowaychuk'981});982</code></pre>983984<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,985as well as the <em>name()</em> function exposed.</p>986987<pre><code>&lt;%= name(firstName, lastName) %>988</code></pre>989990<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>991992<p>Registers dynamic view helpers. Dynamic view helpers993are simply functions which accept <em>req</em>, <em>res</em>, and are994evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function995becomes the local variable it is associated with.</p>996997<pre><code>app.dynamicHelpers({998    session: function(req, res){999        return req.session;1000    }1001});1002</code></pre>10031004<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>10051006<pre><code>&lt;%= session.name %&gt;1007</code></pre>10081009<h3 id="app-mounted-fn-">app.mounted(fn)</h3>10101011<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>10121013<pre><code>var app = express.createServer(),1014    blog = express.createServer();10151016blog.mounted(function(parent){1017    // parent is app1018    // "this" is blog1019});10201021app.use(blog);1022</code></pre>10231024<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>10251026<p>Register the given template engine <em>exports</em>1027as <em>ext</em>. For example we may wish to map ".html"1028files to jade:</p>10291030<pre><code> app.register('.html', require('jade'));1031</code></pre>10321033<p>This is also useful for libraries that may not1034match extensions correctly. For example my haml.js1035library is installed from npm as "hamljs" so instead1036of layout.hamljs, we can register the engine as ".haml":</p>10371038<pre><code> app.register('.haml', require('haml-js'));1039</code></pre>10401041<p>For engines that do not comply with the Express1042specification, we can also wrap their api this way.</p>10431044<pre><code> app.register('.foo', {1045     render: function(str, options) {1046         // perhaps their api is1047         // foo.toHTML(str, options);1048     }1049 });1050</code></pre>10511052<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>10531054<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1055connections will be accepted via <em>INADDR_ANY</em>.</p>10561057<pre><code>app.listen();1058app.listen(3000);1059app.listen(3000, 'n.n.n.n');1060</code></pre>10611062<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>10631064<pre><code>app.listen('/tmp/express.sock');1065</code></pre>10661067<p>Then try it out:</p>10681069<pre><code>$ telnet /tmp/express.sock1070GET / HTTP/1.110711072HTTP/1.1 200 OK1073Content-Type: text/plain1074Content-Length: 1110751076Hello World1077</code></pre>10781079</div>1080			</div>1081		</div>1082	</body>1083</html>