Skip to content
Myr

removed old 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 785ac87 · Browse files · 31 files+0 added−5316 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

31 files+0 added−5316 removed

  • other:+0 added−5316 removed

31 files+0 added−5316 removed

deleted:docs/images/apps/clickdummy.pngbinary

A binary file, deleted.

deleted:docs/images/apps/developmentseed.pngbinary

A binary file, deleted.

deleted:docs/images/apps/e-resistable.pngbinary

A binary file, deleted.

deleted:docs/images/apps/learnboost.pngbinary

A binary file, deleted.

deleted:docs/images/apps/markupio.pngbinary

A binary file, deleted.

deleted:docs/images/apps/nodeko.pngbinary

A binary file, deleted.

deleted:docs/images/apps/opowerjobs.pngbinary

A binary file, deleted.

deleted:docs/images/apps/scrabbly.pngbinary

A binary file, deleted.

deleted:docs/images/apps/storify.pngbinary

A binary file, deleted.

deleted:docs/images/apps/toptwittertrends.pngbinary

A binary file, deleted.

deleted:docs/images/apps/widescript.pngbinary

A binary file, deleted.

deleted:docs/images/bg.jpgbinary

A binary file, deleted.

deleted:docs/images/bg.tile.jpgbinary

A binary file, deleted.

deleted:docs/images/logo.pngbinary

A binary file, deleted.

deleted:docs/images/top.pngbinary

A binary file, deleted.

deleted:docs/layout/foot.html-4 removed
deleted:docs/layout/head.html-193 removed
1<html>2 <head>3 <title>Express - node web framework</title>4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">5 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>6 <style>7 #tagline {8 margin-left: 75px;9 margin-bottom: 30px;10 color: rgba(255,255,255,0.7); }11 html {12 background: #1c1c1c url(images/bg.tile.jpg); }1314 body {15 margin: 0;16 padding-bottom: 30px;17 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";18 font-size: 14px;19 line-height: 1.5;20 -webkit-font-smoothing: antialiased;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, h4 {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; }50 h4 {51 margin-left: 10px;52 font-size: 14px;53 }5455 pre {56 margin: 20px 10px;57 padding: 25px 20px;58 background: rgba(0,0,0,0.5);59 border: 1px solid #323232;60 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);62 -webkit-border-radius: 5px;63 -moz-border-radius: 5px; }6465 code {66 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6768 ul {69 margin: 15px 0;70 padding: 0 0 0 35px; }71 ul li {72 margin: 0;73 padding: 2px 0;74 list-style: square; }75 ul li ul {76 margin: 0;77 padding-left: 12px;78 }7980 .man-name, #Express { display:none; }8182 .sect {83 margin-left: 40px; }84 img {85 margin-left: 20px;86 margin-bottom: 15px;87 }8889 #logo {90 display: block;91 margin-left: 30%;92 margin-bottom: 30px;93 width: 194px;94 height: 51px;95 background: url(images/logo.png) 0 0 no-repeat;96 text-indent: -99999px; }97 #logo:hover {98 opacity: 0.7; }99 #logo:active {100 opacity: 0.3; }101102 #ribbon {103 position: fixed;104 top: 0;105 right: 0;106 z-index: 2; }107108 #wrapper {109 width: 100%;110 min-height: 800px;111 background: url(images/top.png) 0 0 repeat-x; }112113 #container {114 margin: 0 auto;115 padding-top: 80px;116 width: 550px; }117118 #toc {119 position: fixed;120 top: 0;121 left: 0;122 margin: 0 0 0 15px;123 padding: 15px;124 height: 100%;125 background: rgba(0,0,0,0.2);126 overflow: auto;127 border-right: 1px solid rgba(255,255,255,0.05);128 }129 #toc li {130 padding: 0;131 list-style: none;132 }133 #toc li a {134 font-size: 11px;135 }136 #menu {137 margin-left: 75px;138 padding: 0;139 padding-bottom: 30px; }140 #menu li {141 display: inline;142 list-style: none; }143 #menu li a {144 display: block;145 float: left;146 margin: 0 2px;147 padding: 3px 15px;148 background: rgba(0,0,0,0.2);149 -webkit-border-radius: 8px;150 -moz-border-radius: 8px;151 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);153 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;154 -webkit-transition-duration: 0.15s;155 -webkit-transition-timing-function: ease-out; }156 #menu li a:hover,157 #menu li a.active {158 background: rgba(0,0,0,0.5); }159 #menu li a:active {160 background: rgba(0,0,0,0.1);161 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);162 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }163 </style>164 <script>165 $(function(){166 $('.section').hide();167 $('.toggle, a.section-title').toggle(function(){168 $(this).siblings('ul').fadeIn(300);169 return false;170 }, function(){171 $(this).siblings('ul').fadeOut(300);172 return false;173 });174 });175 </script>176 </head>177 <body>178 <a href='http://github.com/visionmedia/express'> 179 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 180 </a>181 <div id="wrapper">182 <div id="container">183 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 184 <p id="tagline">185 High performance, high class web development for186 <a href="http://nodejs.org">Node.js</a>187 </p>188 <ul id="menu">189 <li><a href="index.html">Home</a></li>190 <li><a href="guide.html">Guide</a></li>191 <li><a href="screencasts.html">Screencasts</a></li>192 <li><a href="applications.html">Applications</a></li>193 </ul>
deleted:docs/applications.html-246 removed
1<html>2 <head>3 <title>Express - node web framework</title>4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">5 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>6 <style>7 #tagline {8 margin-left: 75px;9 margin-bottom: 30px;10 color: rgba(255,255,255,0.7); }11 html {12 background: #1c1c1c url(images/bg.tile.jpg); }1314 body {15 margin: 0;16 padding-bottom: 30px;17 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";18 font-size: 14px;19 line-height: 1.5;20 -webkit-font-smoothing: antialiased;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, h4 {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; }50 h4 {51 margin-left: 10px;52 font-size: 14px;53 }5455 pre {56 margin: 20px 10px;57 padding: 25px 20px;58 background: rgba(0,0,0,0.5);59 border: 1px solid #323232;60 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);62 -webkit-border-radius: 5px;63 -moz-border-radius: 5px; }6465 code {66 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6768 ul {69 margin: 15px 0;70 padding: 0 0 0 35px; }71 ul li {72 margin: 0;73 padding: 2px 0;74 list-style: square; }75 ul li ul {76 margin: 0;77 padding-left: 12px;78 }7980 .man-name, #Express { display:none; }8182 .sect {83 margin-left: 40px; }84 img {85 margin-left: 20px;86 margin-bottom: 15px;87 }8889 #logo {90 display: block;91 margin-left: 30%;92 margin-bottom: 30px;93 width: 194px;94 height: 51px;95 background: url(images/logo.png) 0 0 no-repeat;96 text-indent: -99999px; }97 #logo:hover {98 opacity: 0.7; }99 #logo:active {100 opacity: 0.3; }101102 #ribbon {103 position: fixed;104 top: 0;105 right: 0;106 z-index: 2; }107108 #wrapper {109 width: 100%;110 min-height: 800px;111 background: url(images/top.png) 0 0 repeat-x; }112113 #container {114 margin: 0 auto;115 padding-top: 80px;116 width: 550px; }117118 #toc {119 position: fixed;120 top: 0;121 left: 0;122 margin: 0 0 0 15px;123 padding: 15px;124 height: 100%;125 background: rgba(0,0,0,0.2);126 overflow: auto;127 border-right: 1px solid rgba(255,255,255,0.05);128 }129 #toc li {130 padding: 0;131 list-style: none;132 }133 #toc li a {134 font-size: 11px;135 }136 #menu {137 margin-left: 75px;138 padding: 0;139 padding-bottom: 30px; }140 #menu li {141 display: inline;142 list-style: none; }143 #menu li a {144 display: block;145 float: left;146 margin: 0 2px;147 padding: 3px 15px;148 background: rgba(0,0,0,0.2);149 -webkit-border-radius: 8px;150 -moz-border-radius: 8px;151 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);153 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;154 -webkit-transition-duration: 0.15s;155 -webkit-transition-timing-function: ease-out; }156 #menu li a:hover,157 #menu li a.active {158 background: rgba(0,0,0,0.5); }159 #menu li a:active {160 background: rgba(0,0,0,0.1);161 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);162 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }163 </style>164 <script>165 $(function(){166 $('.section').hide();167 $('.toggle, a.section-title').toggle(function(){168 $(this).siblings('ul').fadeIn(300);169 return false;170 }, function(){171 $(this).siblings('ul').fadeOut(300);172 return false;173 });174 });175 </script>176 </head>177 <body>178 <a href='http://github.com/visionmedia/express'> 179 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 180 </a>181 <div id="wrapper">182 <div id="container">183 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 184 <p id="tagline">185 High performance, high class web development for186 <a href="http://nodejs.org">Node.js</a>187 </p>188 <ul id="menu">189 <li><a href="index.html">Home</a></li>190 <li><a href="guide.html">Guide</a></li>191 <li><a href="screencasts.html">Screencasts</a></li>192 <li><a href="applications.html">Applications</a></li>193 </ul>194195196<br />197198199<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>200201<p><a href="http://learnboost.com"><img src="images/apps/learnboost.png" alt="LearnBoost" /></a></p>202203<p><a href="http://storify.com">Storify</a> lets you turn what people post on social media websites into compelling stories.</p>204205<p><a href="http://storify.com"><img src="images/apps/storify.png" alt="Storify" /></a></p>206207<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>208209<p><a href="http://pakistansurvey.org"><img src="images/apps/developmentseed.png" alt="Pakistan Survey" /></a></p>210211<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>212213<p><a href="http://markup.io"><img src="images/apps/markupio.png" alt="Markup.IO" /></a></p>214215<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>216217<p><a href="http://scrabb.ly"><img src="images/apps/scrabbly.png" alt="Online Realtime Scrabble" /></a></p>218219<p><a href="http://clickdummy.net/">ClickDummy</a> is a rapid mockup prototyping application for designers and dummies.</p>220221<p><a href="http://clickdummy.net"><img src="images/apps/clickdummy.png" alt="Mockup Prototying" /></a></p>222223<p><a href="http://nodeknockout.com">Node Knockout</a> organized the first ever node-specific competition with hundreds of contestants.</p>224225<p><a href="http://nodeknockout.com"><img src="images/apps/nodeko.png" alt="Node Knockout Competition Express" /></a></p>226227<p><a href="http://widescript.com">Widescript</a> is an innovative app that helps you focus and interact with your texts &ndash; on your desktop, your couch or on the go.</p>228229<p><a href="http://widescript.com"><img src="images/apps/widescript.png" alt="Widescript" /></a></p>230231<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>232233<p><a href="http://www.e-resistible.co.uk"><img src="images/apps/e-resistable.png" alt="Online Takeaway" /></a></p>234235<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>236237<p><a href="http://toptwittertrends.com"><img src="images/apps/toptwittertrends.png" alt="Twitter Trends" /></a></p>238239<br />240241242<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>243 </div>244 </div>245 </body>246</html>
deleted:docs/applications.md-47 removed
deleted:docs/contrib.html-240 removed
1<html>2 <head>3 <title>Express - node web framework</title>4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">5 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>6 <style>7 #tagline {8 margin-left: 75px;9 margin-bottom: 30px;10 color: rgba(255,255,255,0.7); }11 html {12 background: #1c1c1c url(images/bg.tile.jpg); }1314 body {15 margin: 0;16 padding-bottom: 30px;17 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";18 font-size: 14px;19 line-height: 1.5;20 -webkit-font-smoothing: antialiased;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, h4 {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; }50 h4 {51 margin-left: 10px;52 font-size: 14px;53 }5455 pre {56 margin: 20px 10px;57 padding: 25px 20px;58 background: rgba(0,0,0,0.5);59 border: 1px solid #323232;60 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);62 -webkit-border-radius: 5px;63 -moz-border-radius: 5px; }6465 code {66 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6768 ul {69 margin: 15px 0;70 padding: 0 0 0 35px; }71 ul li {72 margin: 0;73 padding: 2px 0;74 list-style: square; }75 ul li ul {76 margin: 0;77 padding-left: 12px;78 }7980 .man-name, #Express { display:none; }8182 .sect {83 margin-left: 40px; }84 img {85 margin-left: 20px;86 margin-bottom: 15px;87 }8889 #logo {90 display: block;91 margin-left: 30%;92 margin-bottom: 30px;93 width: 194px;94 height: 51px;95 background: url(images/logo.png) 0 0 no-repeat;96 text-indent: -99999px; }97 #logo:hover {98 opacity: 0.7; }99 #logo:active {100 opacity: 0.3; }101102 #ribbon {103 position: fixed;104 top: 0;105 right: 0;106 z-index: 2; }107108 #wrapper {109 width: 100%;110 min-height: 800px;111 background: url(images/top.png) 0 0 repeat-x; }112113 #container {114 margin: 0 auto;115 padding-top: 80px;116 width: 550px; }117118 #toc {119 position: fixed;120 top: 0;121 left: 0;122 margin: 0 0 0 15px;123 padding: 15px;124 height: 100%;125 background: rgba(0,0,0,0.2);126 overflow: auto;127 border-right: 1px solid rgba(255,255,255,0.05);128 }129 #toc li {130 padding: 0;131 list-style: none;132 }133 #toc li a {134 font-size: 11px;135 }136 #menu {137 margin-left: 75px;138 padding: 0;139 padding-bottom: 30px; }140 #menu li {141 display: inline;142 list-style: none; }143 #menu li a {144 display: block;145 float: left;146 margin: 0 2px;147 padding: 3px 15px;148 background: rgba(0,0,0,0.2);149 -webkit-border-radius: 8px;150 -moz-border-radius: 8px;151 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);153 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;154 -webkit-transition-duration: 0.15s;155 -webkit-transition-timing-function: ease-out; }156 #menu li a:hover,157 #menu li a.active {158 background: rgba(0,0,0,0.5); }159 #menu li a:active {160 background: rgba(0,0,0,0.1);161 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);162 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }163 </style>164 <script>165 $(function(){166 $('.section').hide();167 $('.toggle, a.section-title').toggle(function(){168 $(this).siblings('ul').fadeIn(300);169 return false;170 }, function(){171 $(this).siblings('ul').fadeOut(300);172 return false;173 });174 });175 </script>176 </head>177 <body>178 <a href='http://github.com/visionmedia/express'> 179 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 180 </a>181 <div id="wrapper">182 <div id="container">183 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 184 <p id="tagline">185 High performance, high class web development for186 <a href="http://nodejs.org">Node.js</a>187 </p>188 <ul id="menu">189 <li><a href="index.html">Home</a></li>190 <li><a href="guide.html">Guide</a></li>191 <li><a href="screencasts.html">Screencasts</a></li>192 <li><a href="applications.html">Applications</a></li>193 </ul>194<h3>Development Dependencies</h3>195196<p>First install the dev dependencies by executing the following command in the repo&rsquo;s directory:</p>197198<pre><code>$ npm install199</code></pre>200201<h3>Running Tests</h3>202203<p>Express uses the <a href="http://github.com/visionmedia/expresso">Expresso</a> TDD204framework to write and run elegant test suites extremely fast. To run all test suites205simply execute:</p>206207<pre><code>$ make test208</code></pre>209210<p>To target specific suites we may specify the files via:</p>211212<pre><code>$ make test TESTS=test/view.test.js213</code></pre>214215<p>To check test coverage run:</p>216217<pre><code>$ make test-cov218</code></pre>219220<h3>Contributions</h3>221222<p>To accept a contribution, you should follow these guidelines:</p>223224<ul>225<li>All tests <em>must</em> pass</li>226<li>Your alterations or additions <em>must</em> include tests</li>227<li>Your commit(s) should be <em>focused</em>, do not commit once for several changes</li>228<li>Do <em>not</em> alter release information such as the <em>version</em>, or <em>History.md</em></li>229<li>Indents are <em>2</em> spaces.</li>230</ul>231232233<h3>Documentation</h3>234235<p>To contribute documentation edit the markdown files in <em>./docs</em>, however236do <em>not</em> run <em>make docs</em>, as they will be re-built and published with each release.</p>237 </div>238 </div>239 </body>240</html>
deleted:docs/contrib.md-37 removed
deleted:docs/executable.html-216 removed
1<html>2 <head>3 <title>Express - node web framework</title>4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">5 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>6 <style>7 #tagline {8 margin-left: 75px;9 margin-bottom: 30px;10 color: rgba(255,255,255,0.7); }11 html {12 background: #1c1c1c url(images/bg.tile.jpg); }1314 body {15 margin: 0;16 padding-bottom: 30px;17 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";18 font-size: 14px;19 line-height: 1.5;20 -webkit-font-smoothing: antialiased;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, h4 {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; }50 h4 {51 margin-left: 10px;52 font-size: 14px;53 }5455 pre {56 margin: 20px 10px;57 padding: 25px 20px;58 background: rgba(0,0,0,0.5);59 border: 1px solid #323232;60 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);62 -webkit-border-radius: 5px;63 -moz-border-radius: 5px; }6465 code {66 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6768 ul {69 margin: 15px 0;70 padding: 0 0 0 35px; }71 ul li {72 margin: 0;73 padding: 2px 0;74 list-style: square; }75 ul li ul {76 margin: 0;77 padding-left: 12px;78 }7980 .man-name, #Express { display:none; }8182 .sect {83 margin-left: 40px; }84 img {85 margin-left: 20px;86 margin-bottom: 15px;87 }8889 #logo {90 display: block;91 margin-left: 30%;92 margin-bottom: 30px;93 width: 194px;94 height: 51px;95 background: url(images/logo.png) 0 0 no-repeat;96 text-indent: -99999px; }97 #logo:hover {98 opacity: 0.7; }99 #logo:active {100 opacity: 0.3; }101102 #ribbon {103 position: fixed;104 top: 0;105 right: 0;106 z-index: 2; }107108 #wrapper {109 width: 100%;110 min-height: 800px;111 background: url(images/top.png) 0 0 repeat-x; }112113 #container {114 margin: 0 auto;115 padding-top: 80px;116 width: 550px; }117118 #toc {119 position: fixed;120 top: 0;121 left: 0;122 margin: 0 0 0 15px;123 padding: 15px;124 height: 100%;125 background: rgba(0,0,0,0.2);126 overflow: auto;127 border-right: 1px solid rgba(255,255,255,0.05);128 }129 #toc li {130 padding: 0;131 list-style: none;132 }133 #toc li a {134 font-size: 11px;135 }136 #menu {137 margin-left: 75px;138 padding: 0;139 padding-bottom: 30px; }140 #menu li {141 display: inline;142 list-style: none; }143 #menu li a {144 display: block;145 float: left;146 margin: 0 2px;147 padding: 3px 15px;148 background: rgba(0,0,0,0.2);149 -webkit-border-radius: 8px;150 -moz-border-radius: 8px;151 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);153 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;154 -webkit-transition-duration: 0.15s;155 -webkit-transition-timing-function: ease-out; }156 #menu li a:hover,157 #menu li a.active {158 background: rgba(0,0,0,0.5); }159 #menu li a:active {160 background: rgba(0,0,0,0.1);161 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);162 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }163 </style>164 <script>165 $(function(){166 $('.section').hide();167 $('.toggle, a.section-title').toggle(function(){168 $(this).siblings('ul').fadeIn(300);169 return false;170 }, function(){171 $(this).siblings('ul').fadeOut(300);172 return false;173 });174 });175 </script>176 </head>177 <body>178 <a href='http://github.com/visionmedia/express'> 179 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 180 </a>181 <div id="wrapper">182 <div id="container">183 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 184 <p id="tagline">185 High performance, high class web development for186 <a href="http://nodejs.org">Node.js</a>187 </p>188 <ul id="menu">189 <li><a href="index.html">Home</a></li>190 <li><a href="guide.html">Guide</a></li>191 <li><a href="screencasts.html">Screencasts</a></li>192 <li><a href="applications.html">Applications</a></li>193 </ul>194<h2>Synopsis</h2>195196<pre><code>express [options] [PATH]197</code></pre>198199<h2>Description</h2>200201<p>The <em>express</em> executable generates apps at the given <strong>PATH</strong> or the202current working directory. Although Express is not bound to a specific203application structure, this executable creates a maintainable base app.</p>204205<h2>Options</h2>206207<pre><code> -s, --sessions Add session support208 -t, --template ENGINE Add template ENGINE support (jade|ejs). Defaults to jade209 -c, --css ENGINE Add stylesheet ENGINE support (less|sass|stylus). Defaults to plain css210 -v, --version Output framework version211 -h, --help Output help information212</code></pre>213 </div>214 </div>215 </body>216</html>
deleted:docs/executable.md-21 removed
deleted:docs/guide.html-1807 removed
1<html>2 <head>3 <title>Express - node web framework</title>4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">5 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>6 <style>7 #tagline {8 margin-left: 75px;9 margin-bottom: 30px;10 color: rgba(255,255,255,0.7); }11 html {12 background: #1c1c1c url(images/bg.tile.jpg); }1314 body {15 margin: 0;16 padding-bottom: 30px;17 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";18 font-size: 14px;19 line-height: 1.5;20 -webkit-font-smoothing: antialiased;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, h4 {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; }50 h4 {51 margin-left: 10px;52 font-size: 14px;53 }5455 pre {56 margin: 20px 10px;57 padding: 25px 20px;58 background: rgba(0,0,0,0.5);59 border: 1px solid #323232;60 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);62 -webkit-border-radius: 5px;63 -moz-border-radius: 5px; }6465 code {66 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6768 ul {69 margin: 15px 0;70 padding: 0 0 0 35px; }71 ul li {72 margin: 0;73 padding: 2px 0;74 list-style: square; }75 ul li ul {76 margin: 0;77 padding-left: 12px;78 }7980 .man-name, #Express { display:none; }8182 .sect {83 margin-left: 40px; }84 img {85 margin-left: 20px;86 margin-bottom: 15px;87 }8889 #logo {90 display: block;91 margin-left: 30%;92 margin-bottom: 30px;93 width: 194px;94 height: 51px;95 background: url(images/logo.png) 0 0 no-repeat;96 text-indent: -99999px; }97 #logo:hover {98 opacity: 0.7; }99 #logo:active {100 opacity: 0.3; }101102 #ribbon {103 position: fixed;104 top: 0;105 right: 0;106 z-index: 2; }107108 #wrapper {109 width: 100%;110 min-height: 800px;111 background: url(images/top.png) 0 0 repeat-x; }112113 #container {114 margin: 0 auto;115 padding-top: 80px;116 width: 550px; }117118 #toc {119 position: fixed;120 top: 0;121 left: 0;122 margin: 0 0 0 15px;123 padding: 15px;124 height: 100%;125 background: rgba(0,0,0,0.2);126 overflow: auto;127 border-right: 1px solid rgba(255,255,255,0.05);128 }129 #toc li {130 padding: 0;131 list-style: none;132 }133 #toc li a {134 font-size: 11px;135 }136 #menu {137 margin-left: 75px;138 padding: 0;139 padding-bottom: 30px; }140 #menu li {141 display: inline;142 list-style: none; }143 #menu li a {144 display: block;145 float: left;146 margin: 0 2px;147 padding: 3px 15px;148 background: rgba(0,0,0,0.2);149 -webkit-border-radius: 8px;150 -moz-border-radius: 8px;151 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);153 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;154 -webkit-transition-duration: 0.15s;155 -webkit-transition-timing-function: ease-out; }156 #menu li a:hover,157 #menu li a.active {158 background: rgba(0,0,0,0.5); }159 #menu li a:active {160 background: rgba(0,0,0,0.1);161 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);162 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }163 </style>164 <script>165 $(function(){166 $('.section').hide();167 $('.toggle, a.section-title').toggle(function(){168 $(this).siblings('ul').fadeIn(300);169 return false;170 }, function(){171 $(this).siblings('ul').fadeOut(300);172 return false;173 });174 });175 </script>176 </head>177 <body>178 <a href='http://github.com/visionmedia/express'> 179 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 180 </a>181 <div id="wrapper">182 <div id="container"><ul id="toc">183184</ul><ul id="toc">185<li><a href="#installation">Installation</a></li>186<li><a href="#creating-a server">Creating A Server</a></li>187<li><a href="#creating-an https server">Creating An HTTPS Server</a></li>188<li><a href="#configuration">Configuration</a></li>189<li><a href="#settings">Settings</a></li>190<li><a href="#routing">Routing</a></li>191<li><a href="#passing-route control">Passing Route Control</a></li>192<li><a href="#middleware">Middleware</a></li>193<li><a href="#route-middleware">Route Middleware</a></li>194<li><a href="#http-methods">HTTP Methods</a></li>195<li><a href="#error-handling">Error Handling</a></li>196<li><a href="#route-param pre-conditions">Route Param Pre-conditions</a></li>197<li><a href="#view-rendering">View Rendering</a></li>198<li><a href="#view-partials">View Partials</a></li>199<li><a href="#view-lookup">View Lookup</a></li>200<li><a href="#template-engines">Template Engines</a></li>201<li><a href="#session-support">Session Support</a></li>202<li><a href="#migration-guide">Migration Guide</a></li>203<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">204<li><a href="#req.header()">header()</a></li>205<li><a href="#req.accepts()">accepts()</a></li>206<li><a href="#req.is()">is()</a></li>207<li><a href="#req.param()">param()</a></li>208<li><a href="#req.get()">get()</a></li>209<li><a href="#req.flash()">flash()</a></li>210<li><a href="#req.isxmlhttprequest">isXMLHttpRequest</a></li>211</ul></li>212<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">213<li><a href="#res.header()">header()</a></li>214<li><a href="#res.charset">charset</a></li>215<li><a href="#res.contenttype()">contentType()</a></li>216<li><a href="#res.attachment()">attachment()</a></li>217<li><a href="#res.sendfile()">sendfile()</a></li>218<li><a href="#res.download()">download()</a></li>219<li><a href="#res.send()">send()</a></li>220<li><a href="#res.redirect()">redirect()</a></li>221<li><a href="#res.cookie()">cookie()</a></li>222<li><a href="#res.clearcookie()">clearCookie()</a></li>223<li><a href="#res.render()">render()</a></li>224<li><a href="#res.partial()">partial()</a></li>225<li><a href="#res.local()">local()</a></li>226<li><a href="#res.locals()">locals()</a></li>227</ul></li>228<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">229<li><a href="#app.set()">set()</a></li>230<li><a href="#app.enable()">enable()</a></li>231<li><a href="#app.enabled()">enabled()</a></li>232<li><a href="#app.disable()">disable()</a></li>233<li><a href="#app.disabled()">disabled()</a></li>234<li><a href="#app.configure()">configure()</a></li>235<li><a href="#app.redirect()">redirect()</a></li>236<li><a href="#app.error()">error()</a></li>237<li><a href="#app.helpers()">helpers()</a></li>238<li><a href="#app.dynamichelpers()">dynamicHelpers()</a></li>239<li><a href="#app.lookup">lookup</a></li>240<li><a href="#app.match">match</a></li>241<li><a href="#app.mounted()">mounted()</a></li>242<li><a href="#app.register()">register()</a></li>243<li><a href="#app.listen()">listen()</a></li>244</ul></li>245</ul>246 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 247 <p id="tagline">248 High performance, high class web development for249 <a href="http://nodejs.org">Node.js</a>250 </p>251 <ul id="menu">252 <li><a href="index.html">Home</a></li>253 <li><a href="guide.html">Guide</a></li>254 <li><a href="screencasts.html">Screencasts</a></li>255 <li><a href="applications.html">Applications</a></li>256 </ul>257<h3 id="installation">Installation</h3>258259<pre><code>$ npm install express260</code></pre>261262<p>or to access the <code>express(1)</code> executable install globally:</p>263264<pre><code>$ npm install -g express265</code></pre>266267<h2>Quick Start</h2>268269<p> The quickest way to get started with express is to utilize the executable <code>express(1)</code> to generate an application as shown below:</p>270271<p> Create the app:</p>272273<pre><code>$ npm install -g express274$ express /tmp/foo &amp;&amp; cd /tmp/foo275</code></pre>276277<p> Install dependencies:</p>278279<pre><code>$ npm install -d280</code></pre>281282<p> Start the server:</p>283284<pre><code>$ node app.js285</code></pre>286287<h3 id="creating-a server">Creating A Server</h3>288289<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>290291<pre><code>var app = require('express').createServer();292293app.get('/', function(req, res){294 res.send('hello world');295});296297app.listen(3000);298</code></pre>299300<h3 id="creating-an https server">Creating An HTTPS Server</h3>301302<p> To initialize a <em>express.HTTPSServer</em> we do the same as above, however we303 pass an options object, accepting <em>key</em>, <em>cert</em> and the others mentioned in node&rsquo;s <a href="http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer">https documentation</a>.</p>304305<pre><code> var app = require('express').createServer({ key: ... });306</code></pre>307308<h3 id="configuration">Configuration</h3>309310<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers311can use the <em>configure()</em> method to setup needs required by the current environment. When312<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment313prior to the environment specific callback.</p>314315<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces316in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.317Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,318otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>319320<pre><code>app.configure(function(){321 app.use(express.methodOverride());322 app.use(express.bodyParser());323 app.use(app.router);324});325326app.configure('development', function(){327 app.use(express.static(__dirname + '/public'));328 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));329});330331app.configure('production', function(){332 var oneYear = 31557600000;333 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));334 app.use(express.errorHandler());335});336</code></pre>337338<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>339340<pre><code> app.configure(function(){341 app.set('views', __dirname + '/views');342 app.set('views');343 // =&gt; "/absolute/path/to/views"344345 app.enable('some feature');346 // same as app.set('some feature', true);347348 app.disable('some feature');349 // same as app.set('some feature', false);350351 app.enabled('some feature')352 // =&gt; false353 });354</code></pre>355356<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>357358<pre><code>$ NODE_ENV=production node app.js359</code></pre>360361<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>362363<h3 id="settings">Settings</h3>364365<p>Express supports the following settings out of the box:</p>366367<ul>368<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>369<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>370<li><em>view engine</em> Default view engine name for views rendered without extensions</li>371<li><em>view options</em> An object specifying global view options</li>372<li><em>view cache</em> Enable view caching (enabled in production)</li>373<li><em>case sensitive routes</em> Enable case-sensitive routing</li>374</ul>375376377<h3 id="routing">Routing</h3>378379<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.380For example we may want to render a user&rsquo;s account for the path <em>/user/12</em>, this381can be done by defining the route below. The values associated to the named placeholders382are available as <code>req.params</code>.</p>383384<pre><code>app.get('/user/:id', function(req, res){385 res.send('user ' + req.params.id);386});387</code></pre>388389<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example390when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>391392<pre><code>\/user\/([^\/]+)\/?393</code></pre>394395<p>Regular expression literals may also be passed for complex uses. Since capture396groups with literal <em>RegExp</em>&rsquo;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>397398<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){399 res.send(req.params);400});401</code></pre>402403<p>Curl requests against the previously defined route:</p>404405<pre><code> $ curl http://dev:3000/user406 [null,null]407 $ curl http://dev:3000/users408 [null,null]409 $ curl http://dev:3000/users/1410 ["1",null]411 $ curl http://dev:3000/users/1..15412 ["1","15"]413</code></pre>414415<p>Below are some route examples, and the associated paths that they416may consume:</p>417418<pre><code> "/user/:id"419 /user/12420421 "/users/:id?"422 /users/5423 /users424425 "/files/*"426 /files/jquery.js427 /files/javascripts/jquery.js428429 "/file/*.*"430 /files/jquery.js431 /files/javascripts/jquery.js432433 "/user/:id/:operation?"434 /user/1435 /user/1/edit436437 "/products.:format"438 /products.json439 /products.xml440441 "/products.:format?"442 /products.json443 /products.xml444 /products445446 "/user/:id.:format?"447 /user/12448 /user/12.json449</code></pre>450451<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>452453<pre><code>var express = require('express')454 , app = express.createServer();455456app.use(express.bodyParser());457458app.post('/', function(req, res){459 res.send(req.body);460});461462app.listen(3000);463</code></pre>464465<p>Typically we may use a &ldquo;dumb&rdquo; placeholder such as &ldquo;/user/:id&rdquo; which has no restrictions, however say for example we are limiting a user id to digits, we may use <em>&lsquo;/user/:id([0-9]+)&rsquo;</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>466467<h3 id="passing-route control">Passing Route Control</h3>468469<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,470the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,471and 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>472473<pre><code>app.get('/users/:id?', function(req, res, next){474 var id = req.params.id;475 if (id) {476 // do something477 } else {478 next();479 }480});481482app.get('/users', function(req, res){483 // do something else484});485</code></pre>486487<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>488489<pre><code>var express = require('express')490 , app = express.createServer();491492var users = [{ name: 'tj' }];493494app.all('/user/:id/:op?', function(req, res, next){495 req.user = users[req.params.id];496 if (req.user) {497 next();498 } else {499 next(new Error('cannot find user ' + req.params.id));500 }501});502503app.get('/user/:id', function(req, res){504 res.send('viewing ' + req.user.name);505});506507app.get('/user/:id/edit', function(req, res){508 res.send('editing ' + req.user.name);509});510511app.put('/user/:id', function(req, res){512 res.send('updating ' + req.user.name);513});514515app.get('*', function(req, res){516 res.send('what???', 404);517});518519app.listen(3000); 520</code></pre>521522<h3 id="middleware">Middleware</h3>523524<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be525passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>526527<pre><code> var express = require('express');528529var app = express.createServer(530 express.logger()531 , express.bodyParser()532 );533</code></pre>534535<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manner.</p>536537<pre><code>app.use(express.logger({ format: ':method :url' }));538</code></pre>539540<p>Typically with connect middleware you would <em>require(&lsquo;connect&rsquo;)</em> like so:</p>541542<pre><code>var connect = require('connect');543app.use(connect.logger());544app.use(connect.bodyParser());545</code></pre>546547<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>548549<pre><code>app.use(express.logger());550app.use(express.bodyParser());551</code></pre>552553<p>Middleware ordering is important, when Connect receives a request the <em>first</em> middleware we pass to <em>createServer()</em> or <em>use()</em> is executed with three parameters, <em>request</em>, <em>response</em>, and a callback function usually named <em>next</em>. When <em>next()</em> is invoked the second middleware will then have it&rsquo;s turn and so on. This is important to note because many middleware depend on each other, for example <em>methodOverride()</em> checks <em>req.body.</em>method<em> for the HTTP method override, however </em>bodyParser()<em> parses the request body and populates </em>req.body<em>. Another example of this is cookie parsing and session support, we must first </em>use()<em> </em>cookieParser()<em> followed by </em>session()_.</p>554555<p>Many Express applications may contain the line <em>app.use(app.router)</em>, while this may appear strange, it&rsquo;s simply the middleware function that contains all defined routes, and performs route lookup based on the current request url and HTTP method. Express allows you to position this middleware, though by default it will be added to the bottom. By positioning the router, we can alter middleware precedence, for example we may want to add error reporting as the <em>last</em> middleware so that any exception passed to <em>next()</em> will be handled by it, or perhaps we want static file serving to have low precedence, allowing our routes to intercept requests to a static file to count downloads etc. This may look a little like below</p>556557<pre><code>app.use(express.logger(...));558app.use(express.bodyParser(...));559app.use(express.cookieParser(...));560app.use(express.session(...));561app.use(app.router);562app.use(express.static(...));563app.use(express.errorHandler(...));564</code></pre>565566<p>First we add <em>logger()</em> so that it may wrap node&rsquo;s <em>req.end()</em> method, providing us with response-time data. Next the request&rsquo;s body will be parsed (if any), followed by cookie parsing and session support, meaning <em>req.session</em> will be defined by the time we hit our routes in <em>app.router</em>. If a request such as <em>GET /javascripts/jquery.js</em> is handled by our routes, and we do not call <em>next()</em> then the <em>static()</em> middleware will never see this request, however if were to define a route as shown below, we can record stats, refuse downloads, consume download credits etc.</p>567568<pre><code>var downloads = {};569570app.use(app.router);571app.use(express.static(__dirname + '/public'));572573app.get('/*', function(req, res, next){574 var file = req.params[0];575 downloads[file] = downloads[file] || 0;576 downloads[file]++;577 next();578});579</code></pre>580581<h3 id="route-middleware">Route Middleware</h3>582583<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>584585<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>586587<pre><code>app.get('/user/:id', function(req, res, next){588 loadUser(req.params.id, function(err, user){589 if (err) return next(err);590 res.send('Viewing user ' + user.name);591 });592});593</code></pre>594595<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>596597<pre><code>function loadUser(req, res, next) {598 // You would fetch your user from the db599 var user = users[req.params.id];600 if (user) {601 req.user = user;602 next();603 } else {604 next(new Error('Failed to load user ' + req.params.id));605 }606}607608app.get('/user/:id', loadUser, function(req, res){609 res.send('Viewing user ' + req.user.name);610});611</code></pre>612613<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>614615<pre><code>function andRestrictToSelf(req, res, next) {616 req.authenticatedUser.id == req.user.id617 ? next()618 : next(new Error('Unauthorized'));619}620621app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){622 res.send('Editing user ' + req.user.name);623});624</code></pre>625626<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>627628<pre><code>function andRestrictTo(role) {629 return function(req, res, next) {630 req.authenticatedUser.role == role631 ? next()632 : next(new Error('Unauthorized'));633 }634}635636app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){637 res.send('Deleted user ' + req.user.name);638});639</code></pre>640641<p>Commonly used &ldquo;stacks&rdquo; of middleware can be passed as an array (<em>applied recursively</em>), which can be mixed and matched to any degree.</p>642643<pre><code>var a = [middleware1, middleware2]644 , b = [middleware3, middleware4]645 , all = [a, b];646647app.get('/foo', a, function(){});648app.get('/bar', a, function(){});649650app.get('/', a, middleware3, middleware4, function(){});651app.get('/', a, b, function(){});652app.get('/', all, function(){});653</code></pre>654655<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>656657<p>There are times when we may want to &ldquo;skip&rdquo; passed remaining route middleware, but continue matching subsequent routes. To do this we invoke <code>next()</code> with the string &ldquo;route&rdquo; <code>next('route')</code>. If no remaining routes match the request url then Express will respond with 404 Not Found.</p>658659<h3 id="http-methods">HTTP Methods</h3>660661<p>We have seen <em>app.get()</em> a few times, however Express also exposes other familiar HTTP verbs in the same manner, such as <em>app.post()</em>, <em>app.del()</em>, etc.</p>662663<p> A common example for <em>POST</em> usage, is when &ldquo;submitting&rdquo; a form. Below we simply set our form method to &ldquo;post&rdquo; in our html, and control will be given to the route we have defined below it.</p>664665<pre><code> &lt;form method="post" action="/"&gt;666 &lt;input type="text" name="user[name]" /&gt;667 &lt;input type="text" name="user[email]" /&gt;668 &lt;input type="submit" value="Submit" /&gt;669 &lt;/form&gt;670</code></pre>671672<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 &ldquo;using&rdquo; the middleware as shown below:</p>673674<pre><code>app.use(express.bodyParser());675</code></pre>676677<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>678679<pre><code>app.post('/', function(req, res){680 console.log(req.body.user);681 res.redirect('back');682});683</code></pre>684685<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&rsquo;s <em>req.body</em> containing the form values.</p>686687<pre><code>app.use(express.bodyParser());688app.use(express.methodOverride());689</code></pre>690691<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>692693<pre><code>&lt;form method="post" action="/"&gt;694 &lt;input type="hidden" name="_method" value="put" /&gt;695 &lt;input type="text" name="user[name]" /&gt;696 &lt;input type="text" name="user[email]" /&gt;697 &lt;input type="submit" value="Submit" /&gt; 698&lt;/form&gt;699700app.put('/', function(){701 console.log(req.body.user);702 res.redirect('back');703});704</code></pre>705706<h3 id="error-handling">Error Handling</h3>707708<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,709or passed to <em>next(err)</em>. Below is an example which serves different pages based on our710ad-hoc <em>NotFound</em> exception:</p>711712<pre><code>function NotFound(msg){713 this.name = 'NotFound';714 Error.call(this, msg);715 Error.captureStackTrace(this, arguments.callee);716}717718NotFound.prototype.__proto__ = Error.prototype;719720app.get('/404', function(req, res){721 throw new NotFound;722});723724app.get('/500', function(req, res){725 throw new Error('keyboard cat!');726});727</code></pre>728729<p>We can call <em>app.error()</em> several times as shown below.730Here we check for an instanceof <em>NotFound</em> and show the731404 page, or we pass on to the next error handler.</p>732733<p>Note that these handlers can be defined anywhere, as they734will be placed below the route handlers on <em>listen()</em>. This735allows for definition within <em>configure()</em> blocks so we can736handle exceptions in different ways based on the environment.</p>737738<pre><code>app.error(function(err, req, res, next){739 if (err instanceof NotFound) {740 res.render('404.jade');741 } else {742 next(err);743 }744});745</code></pre>746747<p>Here we assume all errors as 500 for the simplicity of748this 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 &ldquo;no such file or directory&rdquo;, we can utilize this in our error handling and display a page specific to this if desired.</p>749750<pre><code>app.error(function(err, req, res){751 res.render('500.jade', {752 error: err753 });754});755</code></pre>756757<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware758to report on exceptions. For example if we wish to output exceptions759in &ldquo;development&rdquo; mode to <em>stderr</em> we can use:</p>760761<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));762</code></pre>763764<p>Also during development we may want fancy html pages to show exceptions765that are passed or thrown, so we can set <em>showStack</em> to true:</p>766767<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));768</code></pre>769770<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>771is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>772773<h3 id="route-param pre-conditions">Route Param Pre-conditions</h3>774775<p>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 <em>/user/:id</em>, we might typically do something like below:</p>776777<pre><code>app.get('/user/:userId', function(req, res, next){778 User.get(req.params.userId, function(err, user){779 if (err) return next(err);780 res.send('user ' + user.name);781 });782}); 783</code></pre>784785<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>786787<pre><code>app.param('userId', function(req, res, next, id){788 User.get(id, function(err, user){789 if (err) return next(err);790 if (!user) return next(new Error('failed to find user'));791 req.user = user;792 next();793 });794});795</code></pre>796797<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>798799<pre><code>app.get('/user/:userId', function(req, res){800 res.send('user ' + req.user.name);801});802</code></pre>803804<h3 id="view-rendering">View Rendering</h3>805806<p>View filenames take the form &ldquo;&lt;name&gt;.&lt;engine&gt;&rdquo;, where &lt;engine&gt; is the name807of the module that will be required. For example the view <em>layout.ejs</em> will808tell the view system to <em>require(&lsquo;ejs&rsquo;)</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 behaviour809<em>app.register()</em> can be used to map engines to file extensions, so that for example &ldquo;foo.html&rdquo; can be rendered by ejs.</p>810811<p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,812and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as813the <em>body</em> local variable in <em>layout.jade</em>.</p>814815<pre><code>app.get('/', function(req, res){816 res.render('index.jade', { title: 'My Site' });817});818</code></pre>819820<p>The new <em>view engine</em> setting allows us to specify our default template engine,821so for example when using jade we could set:</p>822823<pre><code>app.set('view engine', 'jade');824</code></pre>825826<p>Allowing us to render with:</p>827828<pre><code>res.render('index');829</code></pre>830831<p>vs:</p>832833<pre><code>res.render('index.jade');834</code></pre>835836<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still837mix and match template engines:</p>838839<pre><code>res.render('another-page.ejs');840</code></pre>841842<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>843844<pre><code>app.set('view options', {845 layout: false846});847</code></pre>848849<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>850851<pre><code>res.render('myview.ejs', { layout: true });852</code></pre>853854<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>855856<pre><code>res.render('page', { layout: 'mylayout' });857</code></pre>858859<p>Otherwise we must specify the extension:</p>860861<pre><code>res.render('page', { layout: 'mylayout.jade' });862</code></pre>863864<p>These paths may also be absolute:</p>865866<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });867</code></pre>868869<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>870871<pre><code>app.set('view options', {872 open: '{{',873 close: '}}'874});875</code></pre>876877<h3 id="view-partials">View Partials</h3>878879<p>The Express view system has built-in support for partials and collections, which are &ldquo;mini&rdquo; views representing a document fragment. For example rather than iterating880in a view to display comments, we could use partial collection:</p>881882<pre><code>partial('comment', { collection: comments });883</code></pre>884885<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>886887<pre><code>partial('comment', comments);888</code></pre>889890<p>When using the partial collection support a few &ldquo;magic&rdquo; locals are provided891for free:</p>892893<ul>894<li><em>firstInCollection</em> true if this is the first object</li>895<li><em>indexInCollection</em> index of the object in the collection</li>896<li><em>lastInCollection</em> true if this is the last object</li>897<li><em>collectionLength</em> length of the collection</li>898</ul>899900901<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(&lsquo;blog/post&rsquo;, 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>902903<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>904905<p><strong>NOTE:</strong> 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.</p>906907<h3 id="view-lookup">View Lookup</h3>908909<p>View lookup is performed relative to the parent view, for example if we had a page view named <em>views/user/list.jade</em>, and within that view we did <em>partial(&lsquo;edit&rsquo;)</em> it would attempt to load <em>views/user/edit.jade</em>, whereas <em>partial(&lsquo;../messages&rsquo;)</em> would load <em>views/messages.jade</em>.</p>910911<p>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 <em>res.render(&lsquo;users&rsquo;)</em> either <em>views/users.jade</em>, or <em>views/users/index.jade</em>.</p>912913<p>When utilizing index views as shown above, we may reference <em>views/users/index.jade</em> from a view in the same directory by <em>partial(&lsquo;users&rsquo;)</em>, and the view system will try <em>../users/index</em>, preventing us from needing to call <em>partial(&lsquo;index&rsquo;)</em>.</p>914915<h3 id="template-engines">Template Engines</h3>916917<p>Below are a few template engines commonly used with Express:</p>918919<ul>920<li><a href="http://github.com/visionmedia/haml.js">Haml</a> haml implementation</li>921<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>922<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>923<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>924<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>925</ul>926927928<h3 id="session-support">Session Support</h3>929930<p>Sessions support can be added by using Connect&rsquo;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>931932<pre><code>app.use(express.cookieParser());933app.use(express.session({ secret: "keyboard cat" }));934</code></pre>935936<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>937938<pre><code>var RedisStore = require('connect-redis')(express);939app.use(express.cookieParser());940app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));941</code></pre>942943<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>944945<pre><code>var RedisStore = require('connect-redis')(express);946app.use(express.bodyParser());947app.use(express.cookieParser());948app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));949950app.post('/add-to-cart', function(req, res){951 // Perhaps we posted several items with a form952 // (use the bodyParser() middleware for this)953 var items = req.body.items;954 req.session.items = items;955 res.redirect('back');956});957958app.get('/add-to-cart', function(req, res){959 // When redirected back to GET /add-to-cart960 // we could check req.session.items &amp;&amp; req.session.items.length961 // to print out a message962 if (req.session.items &amp;&amp; req.session.items.length) {963 req.flash('info', 'You have %s items in your cart', req.session.items.length);964 }965 res.render('shopping-cart');966});967</code></pre>968969<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>970971<h3 id="migration-guide">Migration Guide</h3>972973<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>974975<h3 id="req.header()">req.header(key[, defaultValue])</h3>976977<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>978979<pre><code>req.header('Host');980req.header('host');981req.header('Accept', '*/*');982</code></pre>983984<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>985986<pre><code>// sent Referrer: http://google.com987988req.header('Referer');989// =&gt; "http://google.com"990991req.header('Referrer');992// =&gt; "http://google.com"993</code></pre>994995<h3 id="req.accepts()">req.accepts(type)</h3>996997<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>998999<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise1000the given <em>type</em> is matched by an exact match, and then subtypes. You1001may pass the subtype such as &ldquo;html&rdquo; which is then converted internally1002to &ldquo;text/html&rdquo; using the mime lookup table.</p>10031004<pre><code>// Accept: text/html1005req.accepts('html');1006// =&gt; true10071008// Accept: text/*; application/json1009req.accepts('html');1010req.accepts('text/html');1011req.accepts('text/plain');1012req.accepts('application/json');1013// =&gt; true10141015req.accepts('image/png');1016req.accepts('png');1017// =&gt; false1018</code></pre>10191020<h3 id="req.is()">req.is(type)</h3>10211022<p>Check if the incoming request contains the <em>Content-Type</em>1023header field, and it contains the give mime <em>type</em>.</p>10241025<pre><code> // With Content-Type: text/html; charset=utf-81026 req.is('html');1027 req.is('text/html');1028 // =&gt; true10291030 // When Content-Type is application/json1031 req.is('json');1032 req.is('application/json');1033 // =&gt; true10341035 req.is('html');1036 // =&gt; false1037</code></pre>10381039<p>Ad-hoc callbacks can also be registered with Express, to perform1040assertions again the request, for example if we need an expressive1041way to check if our incoming request is an image, we can register <em>&ldquo;an image&rdquo;</em>1042callback:</p>10431044<pre><code> app.is('an image', function(req){1045 return 0 == req.headers['content-type'].indexOf('image');1046 });1047</code></pre>10481049<p>Now within our route callbacks, we can use to to assert content types1050such as <em>&ldquo;image/jpeg&rdquo;</em>, <em>&ldquo;image/png&rdquo;</em>, etc.</p>10511052<pre><code> app.post('/image/upload', function(req, res, next){1053 if (req.is('an image')) {1054 // do something1055 } else {1056 next();1057 }1058 });1059</code></pre>10601061<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you1062can perform any request assertion you wish.</p>10631064<p>Wildcard matches can also be made, simplifying our example above for <em>&ldquo;an image&rdquo;</em>, by asserting the <em>subtype</em> only:</p>10651066<pre><code>req.is('image/*');1067</code></pre>10681069<p>We may also assert the <em>type</em> as shown below, which would return true for <em>&ldquo;application/json&rdquo;</em>, and <em>&ldquo;text/json&rdquo;</em>.</p>10701071<pre><code>req.is('*/json');1072</code></pre>10731074<h3 id="req.param()">req.param(name[, default])</h3>10751076<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>10771078<ul>1079<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>1080<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1081<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1082</ul>108310841085<p>To utilize urlencoded request bodies, <em>req.body</em>1086should be an object. This can be done by using1087the _express.bodyParser middleware.</p>10881089<h3 id="req.get()">req.get(field, param)</h3>10901091<p> Get <em>field</em>&rsquo;s <em>param</em> value, defaulting to &lsquo;&rsquo; when the <em>param</em>1092 or <em>field</em> is not present.</p>10931094<pre><code> req.get('content-disposition', 'filename');1095 // =&gt; "something.png"10961097 req.get('Content-Type', 'boundary');1098 // =&gt; "--foo-bar-baz"1099</code></pre>11001101<h3 id="req.flash()">req.flash(type[, msg])</h3>11021103<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>11041105<pre><code>req.flash('info', 'email sent');1106req.flash('error', 'email delivery failed');1107req.flash('info', 'email re-sent');1108// =&gt; 211091110req.flash('info');1111// =&gt; ['email sent', 'email re-sent']11121113req.flash('info');1114// =&gt; []11151116req.flash();1117// =&gt; { error: ['email delivery failed'], info: [] }1118</code></pre>11191120<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>11211122<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1123</code></pre>11241125<h3 id="req.isxmlhttprequest">req.isXMLHttpRequest</h3>11261127<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1128to see if it was issued by an <em>XMLHttpRequest</em>:</p>11291130<pre><code>req.xhr1131req.isXMLHttpRequest1132</code></pre>11331134<h3 id="res.header()">res.header(key[, val])</h3>11351136<p>Get or set the response header <em>key</em>.</p>11371138<pre><code>res.header('Content-Length');1139// =&gt; undefined11401141res.header('Content-Length', 123);1142// =&gt; 12311431144res.header('Content-Length');1145// =&gt; 1231146</code></pre>11471148<h3 id="res.charset">res.charset</h3>11491150<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 &ldquo;utf8&rdquo;, so we may explicitly set the charset before rendering a template:</p>11511152<pre><code>res.charset = 'ISO-8859-1';1153res.render('users');1154</code></pre>11551156<p>or before responding with <code>res.send()</code>:</p>11571158<pre><code>res.charset = 'ISO-8859-1';1159res.send(str);1160</code></pre>11611162<p>or with node&rsquo;s <code>res.end()</code>:</p>11631164<pre><code>res.charset = 'ISO-8859-1';1165res.header('Content-Type', 'text/plain');1166res.end(str);1167</code></pre>11681169<h3 id="res.contenttype()">res.contentType(type)</h3>11701171<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>11721173<pre><code> var filename = 'path/to/image.png';1174 res.contentType(filename);1175 // Content-Type is now "image/png"1176</code></pre>11771178<p>A literal <em>Content-Type</em> works as well:</p>11791180<pre><code> res.contentType('application/json');1181</code></pre>11821183<p>Or simply the extension without leading <code>.</code>:</p>11841185<pre><code> res.contentType('json');1186</code></pre>11871188<h3 id="res.attachment()">res.attachment([filename])</h3>11891190<p>Sets the <em>Content-Disposition</em> response header to &ldquo;attachment&rdquo;, with optional <em>filename</em>.</p>11911192<pre><code> res.attachment('path/to/my/image.png');1193</code></pre>11941195<h3 id="res.sendfile()">res.sendfile(path[, options[, callback]])</h3>11961197<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>11981199<pre><code>res.sendfile('path/to/my.file');1200</code></pre>12011202<p>This method accepts an optional callback which is called when1203an 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>12041205<pre><code>res.sendfile(path, function(err){1206 if (err) {1207 next(err);1208 } else {1209 console.log('transferred %s', path);1210 }1211});1212</code></pre>12131214<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>12151216<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1217 // handle1218});1219</code></pre>12201221<h3 id="res.download()">res.download(file[, filename[, callback[, callback2]]])</h3>12221223<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>12241225<pre><code>res.download('path/to/image.png');1226res.download('path/to/image.png', 'foo.png');1227</code></pre>12281229<p>This is equivalent to:</p>12301231<pre><code>res.attachment(file);1232res.sendfile(file);1233</code></pre>12341235<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>. Within this callback you may still respond, as the header has not been sent.</p>12361237<pre><code>res.download(path, 'expenses.doc', function(err){1238 // handle1239});1240</code></pre>12411242<p>An optional second callback, <em>callback2</em> may be given to allow you to act on connection related errors, however you should not attempt to respond.</p>12431244<pre><code>res.download(path, function(err){1245 // error or finished1246}, function(err){1247 // connection related error1248});1249</code></pre>12501251<h3 id="res.send()">res.send(body|status[, headers|status[, status]])</h3>12521253<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1254objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>12551256<pre><code> res.send(); // 2041257 res.send(new Buffer('wahoo'));1258 res.send({ some: 'json' });1259 res.send('&lt;p&gt;some html&lt;/p&gt;');1260 res.send('Sorry, cant find that', 404);1261 res.send('text', { 'Content-Type': 'text/plain' }, 201);1262 res.send(404);1263</code></pre>12641265<p>By default the <em>Content-Type</em> response header is set, however if explicitly1266assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1267it will not be set again.</p>12681269<p>Note that this method <em>end()</em>s the response, so you will want to use node&rsquo;s <em>res.write()</em> for multiple writes or streaming.</p>12701271<h3 id="res.redirect()">res.redirect(url[, status])</h3>12721273<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>12741275<pre><code>res.redirect('/', 301);1276res.redirect('/account');1277res.redirect('http://google.com');1278res.redirect('home');1279res.redirect('back');1280</code></pre>12811282<p>Express supports &ldquo;redirect mapping&rdquo;, which by default provides <em>home</em>, and <em>back</em>.1283The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1284the &ldquo;home&rdquo; setting and defaults to &ldquo;/&rdquo;.</p>12851286<h3 id="res.cookie()">res.cookie(name, val[, options])</h3>12871288<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>12891290<pre><code>// "Remember me" for 15 minutes 1291res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1292</code></pre>12931294<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>12951296<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });1297</code></pre>12981299<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieParser</em> middleware, which provides the <em>req.cookies</em> object:</p>13001301<pre><code>app.use(express.cookieParser());13021303app.get('/', function(req, res){1304 // use req.cookies.rememberme1305});1306</code></pre>13071308<h3 id="res.clearcookie()">res.clearCookie(name[, options])</h3>13091310<p>Clear cookie <em>name</em> by setting &ldquo;expires&rdquo; far in the past.</p>13111312<pre><code>res.clearCookie('rememberme');1313</code></pre>13141315<h3 id="res.render()">res.render(view[, options[, fn]])</h3>13161317<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1318When a callback function is given a response will <em>not</em> be made1319automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>13201321<p>The <em>options</em> passed are the local variables as well, for example if we want to expose &ldquo;user&rdquo; to the view, and prevent a local we do so within the same object:</p>13221323<pre><code>var user = { name: 'tj' };1324res.render('index', { layout: false, user: user });1325</code></pre>13261327<h3 id="res.partial()">res.partial(view[, options])</h3>13281329<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1330to the view as a local variable.</p>13311332<ul>1333<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1334<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>13351336<ul>1337<li>as: &lsquo;something&rsquo; will add the <em>something</em> local variable</li>1338<li>as: this will use the collection value as the template context</li>1339<li>as: global will merge the collection value&rsquo;s properties with <em>locals</em></li>1340</ul>1341</li>1342<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1343For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1344</ul>134513461347<p>The following are equivalent, and the name of collection value when passed1348to the partial will be <em>movie</em> as derived from the name.</p>13491350<pre><code>partial('theatre/movie.jade', { collection: movies });1351partial('theatre/movie.jade', movies);1352partial('movie.jade', { collection: movies });1353partial('movie.jade', movies);1354partial('movie', movies);1355// In view: movie.director1356</code></pre>13571358<p>To change the local from <em>movie</em> to <em>video</em> we can use the &ldquo;as&rdquo; option:</p>13591360<pre><code>partial('movie', { collection: movies, as: 'video' });1361// In view: video.director1362</code></pre>13631364<p>Also we can make our movie the value of <em>this</em> within our view so that instead1365of <em>movie.director</em> we could use <em>this.director</em>.</p>13661367<pre><code>partial('movie', { collection: movies, as: this });1368// In view: this.director1369</code></pre>13701371<p>Another alternative is to &ldquo;expand&rdquo; the properties of the collection item into1372pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>13731374<pre><code>partial('movie', { collection: movies, as: global });1375// In view: director1376</code></pre>13771378<p>This same logic applies to a single partial object usage:</p>13791380<pre><code>partial('movie', { object: movie, as: this });1381// In view: this.director13821383partial('movie', { object: movie, as: global });1384// In view: director13851386partial('movie', { object: movie, as: 'video' });1387// In view: video.director13881389partial('movie', { object: movie });1390// In view: movie.director1391</code></pre>13921393<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&rsquo;s local variable name is derived from the view name:</p>13941395<pre><code>var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1396partial('movie', movie)1397// =&gt; In view: movie.director1398</code></pre>13991400<p>The exception of this, is when a &ldquo;plain&rdquo; object, aka &ldquo;{}&rdquo; or &ldquo;new Object&rdquo; is passed, which is considered an object with local variable. For example some may expect a &ldquo;movie&rdquo; local with the following, however since it is a plain object &ldquo;director&rdquo; and &ldquo;title&rdquo; are simply locals:</p>14011402<pre><code>var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1403partial('movie', movie)1404</code></pre>14051406<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>14071408<pre><code> partial('movie', { locals: { movie: movie }})1409 partial('movie', { movie: movie })1410 partial('movie', { object: movie })1411</code></pre>14121413<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>14141415<pre><code>app.get('/users', function(req, res){1416 if (req.xhr) {1417 // respond with the each user in the collection1418 // passed to the "user" view1419 res.partial('user', users);1420 } else {1421 // respond with layout, and users page1422 // which internally does partial('user', users)1423 // along with other UI1424 res.render('users', { users: users });1425 }1426});1427</code></pre>14281429<h3 id="res.local()">res.local(name[, val])</h3>14301431<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>14321433<pre><code> app.all('/movie/:id', function(req, res, next){1434 Movie.get(req.params.id, function(err, movie){1435 // Assigns res.locals.movie = movie1436 res.local('movie', movie);1437 });1438 });14391440 app.get('/movie/:id', function(req, res){1441 // movie is already a local, however we1442 // can pass more if we wish1443 res.render('movie', { displayReviews: true });1444 });1445</code></pre>14461447<h3 id="res.locals()">res.locals(obj)</h3>14481449<p> Assign several locals with the given <em>obj</em>. The following are equivalent:</p>14501451<pre><code> res.local('foo', bar);1452 res.local('bar', baz);14531454 res.locals({ foo: bar, bar: baz });1455</code></pre>14561457<h3 id="app.set()">app.set(name[, val])</h3>14581459<p>Apply an application level setting <em>name</em> to <em>val</em>, or1460get the value of <em>name</em> when <em>val</em> is not present:</p>14611462<pre><code>app.set('views', __dirname + '/views');1463app.set('views');1464// =&gt; ...path...1465</code></pre>14661467<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>14681469<pre><code>app.settings.views1470// =&gt; ...path...1471</code></pre>14721473<h3 id="app.enable()">app.enable(name)</h3>14741475<p>Enable the given setting <em>name</em>:</p>14761477<pre><code>app.enable('some arbitrary setting');1478app.set('some arbitrary setting');1479// =&gt; true14801481app.enabled('some arbitrary setting');1482// =&gt; true1483</code></pre>14841485<h3 id="app.enabled()">app.enabled(name)</h3>14861487<p>Check if setting <em>name</em> is enabled:</p>14881489<pre><code>app.enabled('view cache');1490// =&gt; false14911492app.enable('view cache');1493app.enabled('view cache');1494// =&gt; true1495</code></pre>14961497<h3 id="app.disable()">app.disable(name)</h3>14981499<p>Disable the given setting <em>name</em>:</p>15001501<pre><code>app.disable('some setting');1502app.set('some setting');1503// =&gt; false15041505app.disabled('some setting');1506// =&gt; false1507</code></pre>15081509<h3 id="app.disabled()">app.disabled(name)</h3>15101511<p>Check if setting <em>name</em> is disabled:</p>15121513<pre><code>app.enable('view cache');15141515app.disabled('view cache');1516// =&gt; false15171518app.disable('view cache');1519app.disabled('view cache');1520// =&gt; true1521</code></pre>15221523<h3 id="app.configure()">app.configure(env|function[, function])</h3>15241525<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>15261527<pre><code>app.configure(function(){1528 // executed for each env1529});15301531app.configure('development', function(){1532 // executed for 'development' only1533});1534</code></pre>15351536<h3 id="app.redirect()">app.redirect(name, val)</h3>15371538<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>15391540<pre><code>app.redirect('google', 'http://google.com');1541</code></pre>15421543<p>Now in a route we may call:</p>15441545<p> res.redirect(&lsquo;google&rsquo;);</p>15461547<p>We may also map dynamic redirects:</p>15481549<pre><code>app.redirect('comments', function(req, res){1550 return '/post/' + req.params.id + '/comments';1551});1552</code></pre>15531554<p>So now we may do the following, and the redirect will dynamically adjust to1555the context of the request. If we called this route with <em>GET /post/12</em> our1556redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>15571558<pre><code>app.get('/post/:id', function(req, res){1559 res.redirect('comments');1560});1561</code></pre>15621563<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>15641565<pre><code>res.redirect('/posts');1566</code></pre>15671568<h3 id="app.error()">app.error(function)</h3>15691570<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1571Note that we may set several error handlers by making several calls to this method, however the handler1572should call <em>next(err)</em> if it does not wish to deal with the exception:</p>15731574<pre><code>app.error(function(err, req, res, next){1575 res.send(err.message, 500);1576});1577</code></pre>15781579<h3 id="app.helpers()">app.helpers(obj)</h3>15801581<p>Registers static view helpers.</p>15821583<pre><code>app.helpers({1584 name: function(first, last){ return first + ', ' + last }1585 , firstName: 'tj'1586 , lastName: 'holowaychuk'1587});1588</code></pre>15891590<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1591as well as the <em>name()</em> function exposed.</p>15921593<pre><code>&lt;%= name(firstName, lastName) %&gt;1594</code></pre>15951596<p>Express also provides a few locals by default:</p>15971598<pre><code>- `settings` the app's settings object1599- `filename` the view's filename1600- `layout(path)` specify the layout from within a view1601</code></pre>16021603<p>This method is aliased as <em>app.locals()</em>.</p>16041605<h3 id="app.dynamichelpers()">app.dynamicHelpers(obj)</h3>16061607<p>Registers dynamic view helpers. Dynamic view helpers1608are simply functions which accept <em>req</em>, <em>res</em>, and are1609evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1610becomes the local variable it is associated with.</p>16111612<pre><code>app.dynamicHelpers({1613 session: function(req, res){1614 return req.session;1615 }1616});1617</code></pre>16181619<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>16201621<pre><code>&lt;%= session.name %&gt;1622</code></pre>16231624<h3 id="app.lookup">app.lookup</h3>16251626<p> The <em>app.lookup</em> http methods returns an array of callback functions1627 associated with the given <em>path</em>.</p>16281629<p> Suppose we define the following routes:</p>16301631<pre><code> app.get('/user/:id', function(){});1632 app.put('/user/:id', function(){});1633 app.get('/user/:id/:op?', function(){});1634</code></pre>16351636<p> We can utilize this lookup functionality to check which routes1637 have been defined, which can be extremely useful for higher level1638 frameworks built on Express.</p>16391640<pre><code> app.lookup.get('/user/:id');1641 // =&gt; [Function]16421643 app.lookup.get('/user/:id/:op?');1644 // =&gt; [Function]16451646 app.lookup.put('/user/:id');1647 // =&gt; [Function]16481649 app.lookup.all('/user/:id');1650 // =&gt; [Function, Function]16511652 app.lookup.all('/hey');1653 // =&gt; []1654</code></pre>16551656<p> To alias <em>app.lookup.VERB()</em>, we can simply invoke <em>app.VERB()</em>1657 without a callback, as a shortcut, for example the following are1658 equivalent:</p>16591660<pre><code> app.lookup.get('/user');1661 app.get('/user');1662</code></pre>16631664<p> Each function returned has the following properties:</p>16651666<pre><code> var fn = app.get('/user/:id/:op?')[0];16671668 fn.regexp1669 // =&gt; /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i16701671 fn.keys1672 // =&gt; ['id', 'op']16731674 fn.path1675 // =&gt; '/user/:id/:op?'16761677 fn.method1678 // =&gt; 'GET'1679</code></pre>16801681<h3 id="app.match">app.match</h3>16821683<p> The <em>app.match</em> http methods return an array of callback functions1684 which match the given <em>url</em>, which may include a query string etc. This1685 is useful when you want reflect on which routes have the opportunity to1686 respond.</p>16871688<p> Suppose we define the following routes:</p>16891690<pre><code> app.get('/user/:id', function(){});1691 app.put('/user/:id', function(){});1692 app.get('/user/:id/:op?', function(){});1693</code></pre>16941695<p> Our match against <strong>GET</strong> will return two functions, since the <em>:op</em>1696 in our second route is optional.</p>16971698<pre><code> app.match.get('/user/1');1699 // =&gt; [Function, Function]1700</code></pre>17011702<p> This second call returns only the callback for <em>/user/:id/:op?</em>.</p>17031704<pre><code> app.match.get('/user/23/edit');1705 // =&gt; [Function]1706</code></pre>17071708<p> We can also use <em>all()</em> to disregard the http method:</p>17091710<pre><code> app.match.all('/user/20');1711 // =&gt; [Function, Function, Function]1712</code></pre>17131714<p> Each function matched has the following properties:</p>17151716<pre><code> var fn = app.match.get('/user/23/edit')[0];17171718 fn.keys1719 // =&gt; ['id', 'op']17201721 fn.params1722 // =&gt; { id: '23', op: 'edit' }17231724 fn.method1725 // =&gt; 'GET'1726</code></pre>17271728<h3 id="app.mounted()">app.mounted(fn)</h3>17291730<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>17311732<pre><code>var app = express.createServer(),1733 blog = express.createServer();17341735blog.mounted(function(parent){1736 // parent is app1737 // "this" is blog1738});17391740app.use(blog);1741</code></pre>17421743<h3 id="app.register()">app.register(ext, exports)</h3>17441745<p>Register the given template engine <em>exports</em>1746as <em>ext</em>. For example we may wish to map &ldquo;.html&rdquo;1747files to jade:</p>17481749<pre><code> app.register('.html', require('jade'));1750</code></pre>17511752<p>This is also useful for libraries that may not1753match extensions correctly. For example my haml.js1754library is installed from npm as &ldquo;hamljs&rdquo; so instead1755of layout.hamljs, we can register the engine as &ldquo;.haml&rdquo;:</p>17561757<pre><code> app.register('.haml', require('haml-js'));1758</code></pre>17591760<p>For engines that do not comply with the Express1761specification, we can also wrap their api this way. Below1762we map <em>.md</em> to render markdown files, rendering the html once1763since it will not change on subsequent calls, and support local substitution1764in the form of &ldquo;{name}&rdquo;.</p>17651766<pre><code> app.register('.md', {1767 compile: function(str, options){1768 var html = md.toHTML(str);1769 return function(locals){1770 return html.replace(/\{([^}]+)\}/g, function(_, name){1771 return locals[name];1772 });1773 };1774 }1775 });1776</code></pre>17771778<h3 id="app.listen()">app.listen([port[, host]])</h3>17791780<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1781connections will be accepted via <em>INADDR_ANY</em>.</p>17821783<pre><code>app.listen();1784app.listen(3000);1785app.listen(3000, 'n.n.n.n');1786</code></pre>17871788<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>17891790<pre><code>app.listen('/tmp/express.sock');1791</code></pre>17921793<p>Then try it out:</p>17941795<pre><code>$ telnet /tmp/express.sock1796GET / HTTP/1.117971798HTTP/1.1 200 OK1799Content-Type: text/plain1800Content-Length: 1118011802Hello World1803</code></pre>1804 </div>1805 </div>1806 </body>1807</html>
deleted:docs/guide.md-1366 removed
1### Installation23 $ npm install express45or to access the `express(1)` executable install globally:67 $ npm install -g express89## Quick Start1011 The quickest way to get started with express is to utilize the executable `express(1)` to generate an application as shown below:1213 Create the app:1415 $ npm install -g express16 $ express /tmp/foo && cd /tmp/foo1718 Install dependencies:1920 $ npm install -d2122 Start the server:2324 $ node app.js2526### Creating A Server2728 To create an instance of the _express.HTTPServer_, simply invoke the _createServer()_ method. With our instance _app_ we can then define routes based on the HTTP verbs, in this example _app.get()_.2930 var app = require('express').createServer();31 32 app.get('/', function(req, res){33 res.send('hello world');34 });35 36 app.listen(3000);3738### Creating An HTTPS Server3940 To initialize a _express.HTTPSServer_ we do the same as above, however we41 pass an options object, accepting _key_, _cert_ and the others mentioned in node's [https documentation](http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer).42 43 var app = require('express').createServer({ key: ... });4445### Configuration4647Express supports arbitrary environments, such as _production_ and _development_. Developers48can use the _configure()_ method to setup needs required by the current environment. When49_configure()_ is called without an environment name it will be run in _every_ environment 50prior to the environment specific callback.5152In the example below we only _dumpExceptions_, and respond with exception stack traces53in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.54Note the use of _app.router_, which can (optionally) be used to mount the application routes,55otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.5657 app.configure(function(){58 app.use(express.methodOverride());59 app.use(express.bodyParser());60 app.use(app.router);61 });62 63 app.configure('development', function(){64 app.use(express.static(__dirname + '/public'));65 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));66 });67 68 app.configure('production', function(){69 var oneYear = 31557600000;70 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));71 app.use(express.errorHandler());72 });7374For similar environments you may also pass several env strings:7576 app.configure('stage', 'prod', function(){77 // config78 });7980For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:8182 app.configure(function(){83 app.set('views', __dirname + '/views');84 app.set('views');85 // => "/absolute/path/to/views"86 87 app.enable('some feature');88 // same as app.set('some feature', true);89 90 app.disable('some feature');91 // same as app.set('some feature', false);92 93 app.enabled('some feature')94 // => false95 });9697To alter the environment we can set the _NODE_ENV_ environment variable, for example:9899 $ NODE_ENV=production node app.js100101This is _very_ important, as many caching mechanisms are _only enabled_ when in production.102103### Settings104105Express supports the following settings out of the box:106107 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.108 * _views_ Root views directory defaulting to **CWD/views**109 * _view engine_ Default view engine name for views rendered without extensions110 * _view cache_ Enable view caching (enabled in production)111 * _charset_ Alter the default charset of "utf-8"112 * _case sensitive routes_ Enable case-sensitive routing113 * _strict routing_ When enabled trailing slashes are no longer ignored114 * _jsonp callback_ Enable _res.send()_ / _res.json()_ transparent jsonp support115116### Routing117118Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.119For example we may want to render a user's account for the path _/user/12_, this120can be done by defining the route below. The values associated to the named placeholders 121are available as `req.params`.122123 app.get('/user/:id', function(req, res){124 res.send('user ' + req.params.id);125 });126127A route is simple a string which is compiled to a _RegExp_ internally. For example128when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:129130 \/user\/([^\/]+)\/?131132Regular expression literals may also be passed for complex uses. Since capture133groups with literal _RegExp_'s are anonymous we can access them directly `req.params`. So our first capture group would be _req.params[0]_ and the second would follow as _req.params[1]_.134135 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){136 res.send(req.params);137 });138139Curl requests against the previously defined route:140141 $ curl http://dev:3000/user142 [null,null]143 $ curl http://dev:3000/users144 [null,null]145 $ curl http://dev:3000/users/1146 ["1",null]147 $ curl http://dev:3000/users/1..15148 ["1","15"]149150Below are some route examples, and the associated paths that they151may consume:152153 "/user/:id"154 /user/12155156 "/users/:id?"157 /users/5158 /users159160 "/files/*"161 /files/jquery.js162 /files/javascripts/jquery.js163164 "/file/*.*"165 /files/jquery.js166 /files/javascripts/jquery.js167 168 "/user/:id/:operation?"169 /user/1170 /user/1/edit171 172 "/products.:format"173 /products.json174 /products.xml175176 "/products.:format?"177 /products.json178 /products.xml179 /products180 181 "/user/:id.:format?"182 /user/12183 /user/12.json184185For example we can __POST__ some json, and echo the json back using the _bodyParser_ middleware which will parse json request bodies (as well as others), and place the result in _req.body_:186187 var express = require('express')188 , app = express.createServer();189190 app.use(express.bodyParser());191192 app.post('/', function(req, res){193 res.send(req.body);194 });195196 app.listen(3000);197198Typically 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 _'/user/:id([0-9]+)'_ which will _not_ match unless the placeholder value contains only digits.199200### Passing Route Control201202We may pass control to the next _matching_ route, by calling the _third_ argument,203the _next()_ function. When a match cannot be made, control is passed back to Connect,204and middleware continue to be invoked in the order that they are added via _use()_. The same is true for several routes which have the same path defined, they will simply be executed in order until one does _not_ call _next()_ and decides to respond.205206 app.get('/users/:id?', function(req, res, next){207 var id = req.params.id;208 if (id) {209 // do something210 } else {211 next();212 }213 });214 215 app.get('/users', function(req, res){216 // do something else217 });218219The _app.all()_ 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 _req.user_.220221 var express = require('express')222 , app = express.createServer();223224 var users = [{ name: 'tj' }];225226 app.all('/user/:id/:op?', function(req, res, next){227 req.user = users[req.params.id];228 if (req.user) {229 next();230 } else {231 next(new Error('cannot find user ' + req.params.id));232 }233 });234235 app.get('/user/:id', function(req, res){236 res.send('viewing ' + req.user.name);237 });238239 app.get('/user/:id/edit', function(req, res){240 res.send('editing ' + req.user.name);241 });242243 app.put('/user/:id', function(req, res){244 res.send('updating ' + req.user.name);245 });246247 app.get('*', function(req, res){248 res.send(404, 'what???');249 });250251 app.listen(3000); 252253### Middleware254255Middleware via [Connect](http://github.com/senchalabs/connect) can be256passed to _express.createServer()_ as you would with a regular Connect server. For example:257258 var express = require('express');259260 var app = express.createServer(261 express.logger()262 , express.bodyParser()263 );264265Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manner.266267 app.use(express.logger({ format: ':method :url' }));268269Typically with connect middleware you would _require('connect')_ like so:270271 var connect = require('connect');272 app.use(connect.logger());273 app.use(connect.bodyParser());274275This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:276277 app.use(express.logger());278 app.use(express.bodyParser());279280Middleware ordering is important, when Connect receives a request the _first_ middleware we pass to _createServer()_ or _use()_ is executed with three parameters, _request_, _response_, and a callback function usually named _next_. When _next()_ is invoked the second middleware will then have it's turn and so on. This is important to note because many middleware depend on each other, for example _methodOverride()_ checks _req.body._method_ for the HTTP method override, however _bodyParser()_ parses the request body and populates _req.body_. Another example of this is cookie parsing and session support, we must first _use()_ _cookieParser()_ followed by _session()_.281282Many Express applications may contain the line _app.use(app.router)_, while this may appear strange, it's simply the middleware function that contains all defined routes, and performs route lookup based on the current request url and HTTP method. Express allows you to position this middleware, though by default it will be added to the bottom. By positioning the router, we can alter middleware precedence, for example we may want to add error reporting as the _last_ middleware so that any exception passed to _next()_ will be handled by it, or perhaps we want static file serving to have low precedence, allowing our routes to intercept requests to a static file to count downloads etc. This may look a little like below283284 app.use(express.logger(...));285 app.use(express.bodyParser(...));286 app.use(express.cookieParser(...));287 app.use(express.session(...));288 app.use(app.router);289 app.use(express.static(...));290 app.use(express.errorHandler(...));291292First we add _logger()_ so that it may wrap node's _req.end()_ method, providing us with response-time data. Next the request's body will be parsed (if any), followed by cookie parsing and session support, meaning _req.session_ will be defined by the time we hit our routes in _app.router_. If a request such as _GET /javascripts/jquery.js_ is handled by our routes, and we do not call _next()_ then the _static()_ middleware will never see this request, however if were to define a route as shown below, we can record stats, refuse downloads, consume download credits etc.293294 var downloads = {};295296 app.use(app.router);297 app.use(express.static(__dirname + '/public'));298299 app.get('/*', function(req, res, next){300 var file = req.params[0];301 downloads[file] = downloads[file] || 0;302 downloads[file]++;303 next();304 });305306307### Route Middleware308309Routes 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.310311Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 312313 app.get('/user/:id', function(req, res, next){314 loadUser(req.params.id, function(err, user){315 if (err) return next(err);316 res.send('Viewing user ' + user.name);317 });318 });319320To 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. 321322 function loadUser(req, res, next) {323 // You would fetch your user from the db324 var user = users[req.params.id];325 if (user) {326 req.user = user;327 next();328 } else {329 next(new Error('Failed to load user ' + req.params.id));330 }331 }332 333 app.get('/user/:id', loadUser, function(req, res){334 res.send('Viewing user ' + req.user.name);335 });336337Multiple 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.338339 function andRestrictToSelf(req, res, next) {340 req.authenticatedUser.id == req.user.id341 ? next()342 : next(new Error('Unauthorized'));343 }344 345 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){346 res.send('Editing user ' + req.user.name);347 });348349Keeping in mind that middleware are simply functions, we can define function that _returns_ the middleware in order to create a more expressive and flexible solution as shown below.350351 function andRestrictTo(role) {352 return function(req, res, next) {353 req.authenticatedUser.role == role354 ? next()355 : next(new Error('Unauthorized'));356 }357 }358 359 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){360 res.send('Deleted user ' + req.user.name);361 });362363Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.364365 var a = [middleware1, middleware2]366 , b = [middleware3, middleware4]367 , all = [a, b];368 369 app.get('/foo', a, function(){});370 app.get('/bar', a, function(){});371 372 app.get('/', a, middleware3, middleware4, function(){});373 app.get('/', a, b, function(){});374 app.get('/', all, function(){});375376For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.377378There are times when we may want to "skip" passed remaining route middleware, but continue matching subsequent routes. To do this we invoke `next()` with the string "route" `next('route')`. If no remaining routes match the request url then Express will respond with 404 Not Found.379380### HTTP Methods381382We have seen _app.get()_ a few times, however Express also exposes other familiar HTTP verbs in the same manner, such as _app.post()_, _app.del()_, etc.383384 A common example for _POST_ 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.385 386 <form method="post" action="/">387 <input type="text" name="user[name]" />388 <input type="text" name="user[email]" />389 <input type="submit" value="Submit" />390 </form>391392By default Express does not know what to do with this request body, so we should add the _bodyParser_ middleware, which will parse _application/x-www-form-urlencoded_ and _application/json_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:393394 app.use(express.bodyParser());395396Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.397398 app.post('/', function(req, res){399 console.log(req.body.user);400 res.redirect('back');401 });402403When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyParser_ so that it can utilize it's _req.body_ containing the form values.404405 app.use(express.bodyParser());406 app.use(express.methodOverride());407408The 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 _PUT_ and _DELETE_ can still be accessed by clients which can use them directly, although _methodOverride_ provides a great solution for forms. Below shows what the usage of _PUT_ might look like:409410 <form method="post" action="/">411 <input type="hidden" name="_method" value="put" />412 <input type="text" name="user[name]" />413 <input type="text" name="user[email]" />414 <input type="submit" value="Submit" /> 415 </form>416417 app.put('/', function(){418 console.log(req.body.user);419 res.redirect('back');420 });421422### Error Handling423424 Error handling middleware are simply middleware with an arity of 4, aka425 the signature _(err, req, res, next)_. When you _next(err)_ an error,426 only these middleware are executed and have a chance to respond. For example:427 428 app.use(app.bodyParser());429 app.use(app.methodOverride());430 app.use(app.router);431 app.use(function(err, req, res, next){432 res.send(500, 'Server error');433 });434435### Route Param Pre-conditions436437Route 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 _/user/:id_, we might typically do something like below:438439 app.get('/user/:userId', function(req, res, next){440 User.get(req.params.userId, function(err, user){441 if (err) return next(err);442 res.send('user ' + user.name);443 });444 }); 445446With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.447448 app.param('userId', function(req, res, next, id){449 User.get(id, function(err, user){450 if (err) return next(err);451 if (!user) return next(new Error('failed to find user'));452 req.user = user;453 next();454 });455 });456457Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:458459 app.get('/user/:userId', function(req, res){460 res.send('user ' + req.user.name);461 });462463### View Rendering464465View filenames take the form "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name466of the module that will be required. For example the view _layout.ejs_ will467tell the view system to _require('ejs')_, the module being loaded must export the method _exports.compile(str, options)_, and return a _Function_ to comply with Express. To alter this behaviour468_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.469470Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,471and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 472the _body_ local variable in _layout.jade_.473474 app.get('/', function(req, res){475 res.render('index.jade', { title: 'My Site' });476 });477478The new _view engine_ setting allows us to specify our default template engine,479so for example when using jade we could set:480481 app.set('view engine', 'jade');482483Allowing us to render with:484485 res.render('index');486487vs:488489 res.render('index.jade');490491When _view engine_ is set, extensions are entirely optional, however we can still492mix and match template engines:493494 res.render('another-page.ejs');495496 To apply application-level locals, or view engine options may be set using _app.local()_ or _app.locals()_, for example if we don't want layouts for most of our templates we may do:497498 app.local('layout', false);499500Which can then be overridden within the _res.render()_ call if desired, and is otherwise functionally equivalent to passing directly to `res.render()`:501502 res.render('myview.ejs', { layout: true });503504When an alternate layout is required, we may also specify a path. For example if we have _view engine_ set to _jade_ and a file named _./views/mylayout.jade_ we can simply pass:505506 res.render('page', { layout: 'mylayout' });507508Otherwise we must specify the extension:509510 res.render('page', { layout: 'mylayout.jade' });511512These paths may also be absolute:513514 res.render('page', { layout: __dirname + '/../../mylayout.jade' });515516### View Partials517518The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating519in a view to display comments, we could use partial collection:520521 partial('comment', { collection: comments });522523If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:524525 partial('comment', comments);526527When using the partial collection support a few "magic" locals are provided528for free:529530 * _firstInCollection_ true if this is the first object531 * _indexInCollection_ index of the object in the collection532 * _lastInCollection_ true if this is the last object533 * _collectionLength_ length of the collection534535Local 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 _partial('blog/post', post)_ it would generate the _post_ local, but the view calling this function had the local _user_, it would be available to the _blog/post_ view as well.536537For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).538539__NOTE:__ 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.540541### View Lookup542543View lookup is performed relative to the parent view, for example if we had a page view named _views/user/list.jade_, and within that view we did _partial('edit')_ it would attempt to load _views/user/edit.jade_, whereas _partial('../messages')_ would load _views/messages.jade_.544545The 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 _res.render('users')_ either _views/users.jade_, or _views/users/index.jade_.546547When utilizing index views as shown above, we may reference _views/users/index.jade_ from a view in the same directory by _partial('users')_, and the view system will try _../users/index_, preventing us from needing to call _partial('index')_.548549### Template Engines550551Below are a few template engines commonly used with Express:552553 * [Haml](http://github.com/visionmedia/haml.js) haml implementation554 * [Jade](http://jade-lang.com) haml.js successor555 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript556 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating557 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node558559### Session Support560561Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieParser_ middleware place above it, which will parse and populate cookie data to _req.cookies_.562563 app.use(express.cookieParser());564 app.use(express.session({ secret: "keyboard cat" }));565566By default the _session_ middleware uses the memory store bundled with Connect, however many implementations exist. For example [connect-redis](http://github.com/visionmedia/connect-redis) supplies a [Redis](http://code.google.com/p/redis/) session store and can be used as shown below:567568 var RedisStore = require('connect-redis')(express);569 app.use(express.cookieParser());570 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));571572Now the _req.session_ and _req.sessionStore_ properties will be accessible to all routes and subsequent middleware. Properties on _req.session_ are automatically saved on a response, so for example if we wish to shopping cart data:573574 var RedisStore = require('connect-redis')(express);575 app.use(express.bodyParser());576 app.use(express.cookieParser());577 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));578579 app.post('/add-to-cart', function(req, res){580 // Perhaps we posted several items with a form581 // (use the bodyParser() middleware for this)582 var items = req.body.items;583 req.session.items = items;584 res.redirect('back');585 });586587 app.get('/add-to-cart', function(req, res){588 // When redirected back to GET /add-to-cart589 // we could check req.session.items && req.session.items.length590 // to print out a message591 if (req.session.items && req.session.items.length) {592 req.notify('info', 'You have %s items in your cart', req.session.items.length);593 }594 res.render('shopping-cart');595 });596597The _req.session_ object also has methods such as _Session#touch()_, _Session#destroy()_, _Session#regenerate()_ among others to maintain and manipulate sessions. For more information view the [Connect Session](http://senchalabs.github.com/connect/middleware-session.html) documentation.598599### Migration Guide600601 Express 1.x developers may reference the [Migration Guide](migrate.html) 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.602603### req.header(key[, defaultValue])604605Get the case-insensitive request header _key_, with optional _defaultValue_:606607 req.header('Host');608 req.header('host');609 req.header('Accept', '*/*');610611The _Referrer_ and _Referer_ header fields are special-cased, either will work:612613 // sent Referrer: http://google.com614615 req.header('Referer');616 // => "http://google.com"617618 req.header('Referrer');619 // => "http://google.com"620621### req.accepts(type)622623Check if the _Accept_ header is present, and includes the given _type_.624625When the _Accept_ header is not present _true_ is returned. Otherwise626the given _type_ is matched by an exact match, and then subtypes. You627may pass the subtype such as "html" which is then converted internally628to "text/html" using the mime lookup table.629630 // Accept: text/html631 req.accepts('html');632 // => true633634 // Accept: text/*; application/json635 req.accepts('html');636 req.accepts('text/html');637 req.accepts('text/plain');638 req.accepts('application/json');639 // => true640641 req.accepts('image/png');642 req.accepts('png');643 // => false644645### req.is(type)646647Check if the incoming request contains the _Content-Type_648header field, and it contains the give mime _type_.649 650 // With Content-Type: text/html; charset=utf-8651 req.is('html');652 req.is('text/html');653 // => true654 655 // When Content-Type is application/json656 req.is('json');657 req.is('application/json');658 // => true659 660 req.is('html');661 // => false662 663Ad-hoc callbacks can also be registered with Express, to perform664assertions again the request, for example if we need an expressive665way to check if our incoming request is an image, we can register _"an image"_666callback:667 668 app.is('an image', function(req){669 return 0 == req.headers['content-type'].indexOf('image');670 });671 672Now within our route callbacks, we can use to to assert content types673such as _"image/jpeg"_, _"image/png"_, etc.674 675 app.post('/image/upload', function(req, res, next){676 if (req.is('an image')) {677 // do something678 } else {679 next();680 }681 });682683Keep in mind this method is _not_ limited to checking _Content-Type_, you684can perform any request assertion you wish.685686Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:687688 req.is('image/*');689690We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.691692 req.is('*/json');693694### req.param(name[, default])695696Return the value of param _name_ when present or _default_.697698 - Checks route params (_req.params_), ex: /user/:id699 - Checks query string params (_req.query_), ex: ?id=12700 - Checks urlencoded body params (_req.body_), ex: id=12701702To utilize urlencoded request bodies, _req.body_703should be an object. This can be done by using704the _express.bodyParser middleware.705706### req.get(field, param)707708 Get _field_'s _param_ value, defaulting to '' when the _param_709 or _field_ is not present.710711 req.get('content-disposition', 'filename');712 // => "something.png"713714 req.get('Content-Type', 'boundary');715 // => "--foo-bar-baz"716717### req.notify(type[, msg])718719Queue flash _msg_ of the given _type_.720721 req.notify('info', 'email sent');722 req.notify('error', 'email delivery failed');723 req.notify('info', 'email re-sent');724 // => 2725726 req.notify('info');727 // => ['email sent', 'email re-sent']728729 req.notify('info');730 // => []731732 req.notify();733 // => { error: ['email delivery failed'], info: [] }734735Flash notification message may also utilize formatters, by default only the %s string and %d integer formatters is available:736737 req.notify('info', 'email delivery to <em>%s</em> from <em>%s</em> failed.', toUser, fromUser);738739Argument HTML is escaped, to prevent XSS, however HTML notification format is valid.740741### req.isXMLHttpRequest742743Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header744to see if it was issued by an _XMLHttpRequest_:745746 req.xhr747 req.isXMLHttpRequest748749### res.header(key[, val])750751Get or set the response header _key_.752753 res.header('Content-Length');754 // => undefined755756 res.header('Content-Length', 123);757 // => 123758 759 res.header('Content-Length');760 // => 123761762### res.charset763764Sets the charset for subsequent `Content-Type` header fields. For example `res.send()` and `res.render()` default to "utf8", so we may explicitly set the charset before rendering a template:765766 res.charset = 'ISO-8859-1';767 res.render('users');768769or before responding with `res.send()`:770771 res.charset = 'ISO-8859-1';772 res.send(str);773774or with node's `res.end()`:775776 res.charset = 'ISO-8859-1';777 res.header('Content-Type', 'text/plain');778 res.end(str);779780### res.contentType(type)781782Sets the _Content-Type_ response header to the given _type_.783784 var filename = 'path/to/image.png';785 res.contentType(filename);786 // Content-Type is now "image/png"787788A literal _Content-Type_ works as well:789790 res.contentType('application/json');791792Or simply the extension without leading `.`:793794 res.contentType('json');795796### res.attachment([filename])797798Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.799800 res.attachment('path/to/my/image.png');801802### res.status(code)803804 Sets the `res.statusCode` property to `code` and returns for chaining:805806 res.status(500).send('Something bad happened');807808 is equivalent to:809 810 res.statusCode = 500;811 res.send('Something bad happened');812813 and:814815 res.send(500, 'Something bad happened');816817### res.sendfile(path[, options[, callback]])818819Used by `res.download()` to transfer an arbitrary file. 820821 res.sendfile('path/to/my.file');822823This method accepts an optional callback which is called when824an error occurs, or when the transfer is complete. By default failures call `next(err)`, however when a callback is supplied you must do this explicitly, or act on the error.825826 res.sendfile(path, function(err){827 if (err) {828 next(err);829 } else {830 console.log('transferred %s', path);831 }832 });833834Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:835836 res.sendfile(path, { bufferSize: 1024 }, function(err){837 // handle838 });839840### res.download(file[, filename[, callback[, callback2]]])841842Transfer the given _file_ as an attachment with optional alternative _filename_.843844 res.download('path/to/image.png');845 res.download('path/to/image.png', 'foo.png');846847This is equivalent to:848849 res.attachment(file);850 res.sendfile(file);851852An optional callback may be supplied as either the second or third argument, which is passed to _res.sendfile()_. Within this callback you may still respond, as the header has not been sent.853854 res.download(path, 'expenses.doc', function(err){855 // handle856 });857858An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.859860 res.download(path, function(err){861 // error or finished862 }, function(err){863 // connection related error864 });865866### res.send(body|status[, body])867868The _res.send()_ method is a high level response utility allowing you to pass869objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:870871 res.send(new Buffer('wahoo'));872 res.send({ some: 'json' });873 res.send(201, { message: 'User created' });874 res.send('<p>some html</p>');875 res.send(404, 'Sorry, cant find that');876 res.send(404); // "Not Found"877 res.send(500); // "Internal Server Error"878879The _Content-Type_ response header is defaulted appropriately unless previously defined via `res.header()` / `res.contentType()` etc.880881Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.882883### res.json(obj|status[, obj])884885 Send an explicit JSON response. This method is ideal for JSON-only APIs, while it is much like _res.send(obj)_, send is not ideal for cases when you want to send for example a single string as JSON, since the default for _res.send(string)_ is text/html.886887 res.json(null);888 res.json({ user: 'tj' });889 res.json(500, 'oh noes!');890 res.json(404, 'I dont have that');891892### res.redirect(url[, status])893894Redirect to the given _url_ with a default response _status_ of 302.895896 res.redirect('/', 301);897 res.redirect('/account');898 res.redirect('http://google.com');899 res.redirect('home');900 res.redirect('back');901902Express supports "redirect mapping", which by default provides _home_, and _back_.903The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes904the "home" setting and defaults to "/".905906### res.cookie(name, val[, options])907908Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc. The _path_ option defaults to the app's "home" setting, which909is typically "/".910911 // "Remember me" for 15 minutes 912 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });913914The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:915916 res.cookie('rememberme', 'yes', { maxAge: 900000 });917918To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:919920 app.use(express.cookieParser());921 922 app.get('/', function(req, res){923 // use req.cookies.rememberme924 });925926### res.clearCookie(name[, options])927928Clear cookie _name_ by setting "expires" far in the past. Much like929_res.cookie()_ the _path_ option also defaults to the "home" setting.930931 res.clearCookie('rememberme');932933### res.render(view[, options[, fn]])934935Render _view_ with the given _options_ and optional callback _fn_.936When a callback function is given a response will _not_ be made937automatically, however otherwise a response of _200_ and _text/html_ is given.938939The _options_ 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:940941 var user = { name: 'tj' };942 res.render('index', { layout: false, user: user });943944This _options_ object is also considered an "options" object. For example 945when you pass the _status_ local, it's not only available to the view, it946sets the response status to this number. This is also useful if a template947engine accepts specific options, such as _debug_, or _compress_. Below948is an example of how one might render an error page, passing the _status_ for949display, as well as it setting _res.statusCode_.950951 res.render('error', { status: 500, message: 'Internal Server Error' });952953### res.partial(view[, options])954955Render _view_ partial with the given _options_. This method is always available956to the view as a local variable.957958- _object_ the object named by _as_ or derived from the view name959- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.960 * as: 'something' will add the _something_ local variable961 * as: this will use the collection value as the template context962 * as: global will merge the collection value's properties with _locals_963964- _collection_ Array of objects, the name is derived from the view name itself. 965 For example _video.html_ will have a object _video_ available to it.966967The following are equivalent, and the name of collection value when passed968to the partial will be _movie_ as derived from the name.969970 partial('theatre/movie.jade', { collection: movies });971 partial('theatre/movie.jade', movies);972 partial('movie.jade', { collection: movies });973 partial('movie.jade', movies);974 partial('movie', movies);975 // In view: movie.director976977To change the local from _movie_ to _video_ we can use the "as" option:978979 partial('movie', { collection: movies, as: 'video' });980 // In view: video.director981982Also we can make our movie the value of _this_ within our view so that instead983of _movie.director_ we could use _this.director_.984985 partial('movie', { collection: movies, as: this });986 // In view: this.director987988Another alternative is to "expand" the properties of the collection item into989pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:990991 partial('movie', { collection: movies, as: global });992 // In view: director993994This same logic applies to a single partial object usage:995996 partial('movie', { object: movie, as: this });997 // In view: this.director998999 partial('movie', { object: movie, as: global });1000 // In view: director10011002 partial('movie', { object: movie, as: 'video' });1003 // In view: video.director10041005 partial('movie', { object: movie });1006 // In view: movie.director10071008When a non-collection (does _not_ have _.length_) is passed as the second argument, it is assumed to be the _object_, after which the object's local variable name is derived from the view name:10091010 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1011 partial('movie', movie)1012 // => In view: movie.director10131014The 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:10151016 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1017 partial('movie', movie)10181019For cases like this where passing a plain object is desired, simply assign it to a key, or use the `object` key which will use the filename-derived variable name. The examples below are equivalent:10201021 partial('movie', { locals: { movie: movie }})1022 partial('movie', { movie: movie })1023 partial('movie', { object: movie })10241025This 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:10261027 app.get('/users', function(req, res){1028 if (req.xhr) {1029 // respond with the each user in the collection1030 // passed to the "user" view1031 res.partial('user', users);1032 } else {1033 // respond with layout, and users page1034 // which internally does partial('user', users)1035 // along with other UI1036 res.render('users', { users: users });1037 }1038 });10391040### res.local(name[, val])10411042Get or set the given local variable _name_. The locals built up for a response are applied to those given to the view rendering methods such as `res.render()`.10431044 app.all('/movie/:id', function(req, res, next){1045 Movie.get(req.params.id, function(err, movie){1046 // Assigns res.locals.movie = movie1047 res.local('movie', movie);1048 });1049 });1050 1051 app.get('/movie/:id', function(req, res){1052 // movie is already a local, however we1053 // can pass more if we wish1054 res.render('movie', { displayReviews: true });1055 });10561057### res.locals(obj)10581059 Assign several locals with the given _obj_. The following are equivalent:1060 1061 res.local('foo', bar);1062 res.local('bar', baz);10631064 res.locals({ foo: bar, bar, baz });10651066### app.set(name[, val])10671068Apply an application level setting _name_ to _val_, or1069get the value of _name_ when _val_ is not present:10701071 app.set('views', __dirname + '/views');1072 app.set('views');1073 // => ...path...10741075Alternatively you may simply access the settings via _app.settings_:10761077 app.settings.views1078 // => ...path...10791080### app.enable(name)10811082Enable the given setting _name_:10831084 app.enable('some arbitrary setting');1085 app.set('some arbitrary setting');1086 // => true10871088 app.enabled('some arbitrary setting');1089 // => true10901091### app.enabled(name)10921093Check if setting _name_ is enabled:10941095 app.enabled('view cache');1096 // => false10971098 app.enable('view cache');1099 app.enabled('view cache');1100 // => true11011102### app.disable(name)11031104Disable the given setting _name_:11051106 app.disable('some setting');1107 app.set('some setting');1108 // => false1109 1110 app.disabled('some setting');1111 // => false11121113### app.disabled(name)11141115Check if setting _name_ is disabled:11161117 app.enable('view cache');11181119 app.disabled('view cache');1120 // => false11211122 app.disable('view cache');1123 app.disabled('view cache');1124 // => true11251126### app.configure(env|function[, function])11271128Define a callback function for the given _env_ (or all environments) with callback _function_:11291130 app.configure(function(){1131 // executed for each env1132 });11331134 app.configure('development', function(){1135 // executed for 'development' only1136 });11371138### app.redirect(name, val)11391140For use with _res.redirect()_ we can map redirects at the application level as shown below:11411142 app.redirect('google', 'http://google.com');11431144Now in a route we may call:11451146 res.redirect('google');11471148We may also map dynamic redirects:11491150 app.redirect('comments', function(req, res){1151 return '/post/' + req.params.id + '/comments';1152 });11531154So now we may do the following, and the redirect will dynamically adjust to1155the context of the request. If we called this route with _GET /post/12_ our1156redirect _Location_ would be _/post/12/comments_.11571158 app.get('/post/:id', function(req, res){1159 res.redirect('comments');1160 });11611162When mounted, _res.redirect()_ will respect the mount-point. For example if a blog app is mounted at _/blog_, the following will redirect to _/blog/posts_:11631164 res.redirect('/posts');11651166### app.locals(obj)11671168Registers static view locals.11691170 app.locals({1171 name: function(first, last){ return first + ', ' + last }1172 , firstName: 'tj'1173 , lastName: 'holowaychuk'1174 });11751176Our view could now utilize the _firstName_ and _lastName_ variables,1177as well as the _name()_ function exposed.11781179 <%= name(firstName, lastName) %>11801181Express also provides a few locals by default:11821183 - `settings` the app's settings object1184 - `layout(path)` specify the layout from within a view11851186### app.dynamicLocals(obj)11871188Registers dynamic view locals. Dynamic locals1189are simply functions which accept _req_, _res_, and are1190evaluated against the _Server_ instance before a view is rendered, and are unique to that specific request. The _return value_ of this function1191becomes the local variable it is associated with.11921193 app.dynamicLocals({1194 session: function(req, res){1195 return req.session;1196 }1197 });11981199All views would now have _session_ available so that session data can be accessed via _session.name_ etc:12001201 <%= session.name %>12021203### app.lookup12041205 The _app.lookup_ http methods returns an array of callback functions1206 associated with the given _path_.12071208 Suppose we define the following routes:1209 1210 app.get('/user/:id', function(){});1211 app.put('/user/:id', function(){});1212 app.get('/user/:id/:op?', function(){});12131214 We can utilize this lookup functionality to check which routes1215 have been defined, which can be extremely useful for higher level1216 frameworks built on Express.12171218 app.lookup.get('/user/:id');1219 // => [Function]12201221 app.lookup.get('/user/:id/:op?');1222 // => [Function]12231224 app.lookup.put('/user/:id');1225 // => [Function]12261227 app.lookup.all('/user/:id');1228 // => [Function, Function]12291230 app.lookup.all('/hey');1231 // => []12321233 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1234 without a callback, as a shortcut, for example the following are1235 equivalent:1236 1237 app.lookup.get('/user');1238 app.get('/user');12391240 Each function returned has the following properties:1241 1242 var fn = app.get('/user/:id/:op?')[0];12431244 fn.regexp1245 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12461247 fn.keys1248 // => ['id', 'op']12491250 fn.path1251 // => '/user/:id/:op?'12521253 fn.method1254 // => 'GET'12551256### app.match12571258 The _app.match_ http methods return an array of callback functions1259 which match the given _url_, which may include a query string etc. This1260 is useful when you want reflect on which routes have the opportunity to1261 respond.12621263 Suppose we define the following routes:12641265 app.get('/user/:id', function(){});1266 app.put('/user/:id', function(){});1267 app.get('/user/:id/:op?', function(){});12681269 Our match against __GET__ will return two functions, since the _:op_1270 in our second route is optional.12711272 app.match.get('/user/1');1273 // => [Function, Function]12741275 This second call returns only the callback for _/user/:id/:op?_.12761277 app.match.get('/user/23/edit');1278 // => [Function]12791280 We can also use _all()_ to disregard the http method:12811282 app.match.all('/user/20');1283 // => [Function, Function, Function]12841285 Each function matched has the following properties:1286 1287 var fn = app.match.get('/user/23/edit')[0];12881289 fn.keys1290 // => ['id', 'op']12911292 fn.params1293 // => { id: '23', op: 'edit' }12941295 fn.method1296 // => 'GET'12971298### app.mounted(fn)12991300Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.13011302 var app = express.createServer(),1303 blog = express.createServer();1304 1305 blog.mounted(function(parent){1306 // parent is app1307 // "this" is blog1308 });1309 1310 app.use(blog);13111312### app.register(ext, exports)13131314Register the given template engine _exports_1315as _ext_. For example we may wish to map ".html"1316files to jade:13171318 app.register('.html', require('jade'));13191320This is also useful for libraries that may not1321match extensions correctly. For example my haml.js1322library is installed from npm as "hamljs" so instead1323of layout.hamljs, we can register the engine as ".haml":13241325 app.register('.haml', require('haml-js'));13261327For engines that do not comply with the Express1328specification, we can also wrap their api this way. Below1329we map _.md_ to render markdown files, rendering the html once1330since it will not change on subsequent calls, and support local substitution1331in the form of "{name}".13321333 app.register('.md', {1334 compile: function(str, options){1335 var html = md.toHTML(str);1336 return function(locals){1337 return html.replace(/\{([^}]+)\}/g, function(_, name){1338 return locals[name];1339 });1340 };1341 }1342 });13431344### app.listen([port[, host]])13451346Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1347connections will be accepted via _INADDR_ANY_.13481349 app.listen();1350 app.listen(3000);1351 app.listen(3000, 'n.n.n.n');13521353The _port_ argument may also be a string representing the path to a unix domain socket:13541355 app.listen('/tmp/express.sock');13561357Then try it out:13581359 $ telnet /tmp/express.sock1360 GET / HTTP/1.113611362 HTTP/1.1 200 OK1363 Content-Type: text/plain1364 Content-Length: 111365 1366 Hello World
deleted:docs/index.html-266 removed
1<html>2 <head>3 <title>Express - node web framework</title>4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">5 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>6 <style>7 #tagline {8 margin-left: 75px;9 margin-bottom: 30px;10 color: rgba(255,255,255,0.7); }11 html {12 background: #1c1c1c url(images/bg.tile.jpg); }1314 body {15 margin: 0;16 padding-bottom: 30px;17 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";18 font-size: 14px;19 line-height: 1.5;20 -webkit-font-smoothing: antialiased;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, h4 {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; }50 h4 {51 margin-left: 10px;52 font-size: 14px;53 }5455 pre {56 margin: 20px 10px;57 padding: 25px 20px;58 background: rgba(0,0,0,0.5);59 border: 1px solid #323232;60 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);62 -webkit-border-radius: 5px;63 -moz-border-radius: 5px; }6465 code {66 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6768 ul {69 margin: 15px 0;70 padding: 0 0 0 35px; }71 ul li {72 margin: 0;73 padding: 2px 0;74 list-style: square; }75 ul li ul {76 margin: 0;77 padding-left: 12px;78 }7980 .man-name, #Express { display:none; }8182 .sect {83 margin-left: 40px; }84 img {85 margin-left: 20px;86 margin-bottom: 15px;87 }8889 #logo {90 display: block;91 margin-left: 30%;92 margin-bottom: 30px;93 width: 194px;94 height: 51px;95 background: url(images/logo.png) 0 0 no-repeat;96 text-indent: -99999px; }97 #logo:hover {98 opacity: 0.7; }99 #logo:active {100 opacity: 0.3; }101102 #ribbon {103 position: fixed;104 top: 0;105 right: 0;106 z-index: 2; }107108 #wrapper {109 width: 100%;110 min-height: 800px;111 background: url(images/top.png) 0 0 repeat-x; }112113 #container {114 margin: 0 auto;115 padding-top: 80px;116 width: 550px; }117118 #toc {119 position: fixed;120 top: 0;121 left: 0;122 margin: 0 0 0 15px;123 padding: 15px;124 height: 100%;125 background: rgba(0,0,0,0.2);126 overflow: auto;127 border-right: 1px solid rgba(255,255,255,0.05);128 }129 #toc li {130 padding: 0;131 list-style: none;132 }133 #toc li a {134 font-size: 11px;135 }136 #menu {137 margin-left: 75px;138 padding: 0;139 padding-bottom: 30px; }140 #menu li {141 display: inline;142 list-style: none; }143 #menu li a {144 display: block;145 float: left;146 margin: 0 2px;147 padding: 3px 15px;148 background: rgba(0,0,0,0.2);149 -webkit-border-radius: 8px;150 -moz-border-radius: 8px;151 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);153 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;154 -webkit-transition-duration: 0.15s;155 -webkit-transition-timing-function: ease-out; }156 #menu li a:hover,157 #menu li a.active {158 background: rgba(0,0,0,0.5); }159 #menu li a:active {160 background: rgba(0,0,0,0.1);161 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);162 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }163 </style>164 <script>165 $(function(){166 $('.section').hide();167 $('.toggle, a.section-title').toggle(function(){168 $(this).siblings('ul').fadeIn(300);169 return false;170 }, function(){171 $(this).siblings('ul').fadeOut(300);172 return false;173 });174 });175 </script>176 </head>177 <body>178 <a href='http://github.com/visionmedia/express'> 179 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 180 </a>181 <div id="wrapper">182 <div id="container">183 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 184 <p id="tagline">185 High performance, high class web development for186 <a href="http://nodejs.org">Node.js</a>187 </p>188 <ul id="menu">189 <li><a href="index.html">Home</a></li>190 <li><a href="guide.html">Guide</a></li>191 <li><a href="screencasts.html">Screencasts</a></li>192 <li><a href="applications.html">Applications</a></li>193 </ul>194<pre><code>var app = express.createServer();195196app.get('/', function(req, res){197 res.send('Hello World');198});199200app.listen(3000);201</code></pre>202203<h2>Features</h2>204205<ul>206<li>Robust routing</li>207<li>Redirection helpers</li>208<li>Dynamic view helpers</li>209<li>Application level view options</li>210<li>Content negotiation</li>211<li>Application mounting</li>212<li>Focus on high performance</li>213<li>View rendering and partials support</li>214<li>Environment based configuration</li>215<li>Session based flash notifications</li>216<li>Built on <a href="http://github.com/senchalabs/connect">Connect</a></li>217<li><a href="executable.html">Executable</a> for generating applications quickly</li>218<li>High test coverage</li>219</ul>220221222<h2>Contributors</h2>223224<p>The following are the major contributors of Express (in no specific order).</p>225226<ul>227<li>TJ Holowaychuk (<a href="http://github.com/visionmedia">visionmedia</a>)</li>228<li>Ciaran Jessup (<a href="http://github.com/ciaranj">ciaranj</a>)</li>229<li>Aaron Heckmann (<a href="http://github.com/aheckmann">aheckmann</a>)</li>230<li>Guillermo Rauch (<a href="http://github.com/guille">guille</a>)</li>231</ul>232233234<h2>Third-Party Modules</h2>235236<p>The following modules compliment or extend Express directly:</p>237238<ul>239<li><a href="http://github.com/visionmedia/express-resource">express-resource</a> provides resourceful routing</li>240<li><a href="http://github.com/visionmedia/express-messages">express-messages</a> flash message notification rendering</li>241<li><a href="http://github.com/visionmedia/express-configuration">express-configure</a> async configuration support (load settings from redis etc)</li>242<li><a href="http://github.com/visionmedia/express-namespace">express-namespace</a> namespaced routing support</li>243<li><a href="http://github.com/visionmedia/express-expose">express-expose</a> expose objects, functions, modules and more to client-side js</li>244<li><a href="https://github.com/visionmedia/express-params">express-params</a> app.param() extensions</li>245<li><a href="https://github.com/LearnBoost/express-mongoose">express-mongoose</a> plugin for easy rendering of Mongoose async Query results</li>246</ul>247248249<h2>More Information</h2>250251<ul>252<li>#express on freenode</li>253<li>Follow <a href="http://twitter.com/tjholowaychuk">tjholowaychuk</a> on twitter for updates</li>254<li><a href="http://groups.google.com/group/express-js">Google Group</a> for discussion</li>255<li>Visit the <a href="http://github.com/visionmedia/express/wiki">Wiki</a></li>256<li><a href="http://hideyukisaito.com/doc/expressjs/">日本語ドキュメンテーション</a> by <a href="https://github.com/hideyukisaito">hideyukisaito</a></li>257<li>Screencast &ndash; <a href="http://bit.ly/eRYu0O">Introduction</a></li>258<li>Screencast &ndash; <a href="http://bit.ly/dU13Fx">View Partials</a></li>259<li>Screencast &ndash; <a href="http://bit.ly/hX4IaH">Route Specific Middleware</a></li>260<li>Screencast &ndash; <a href="http://bit.ly/eNqmVs">Route Path Placeholder Preconditions</a></li>261</ul>262263 </div>264 </div>265 </body>266</html>
deleted:docs/index.md-54 removed
deleted:docs/migrate.html-394 removed
1<html>2 <head>3 <title>Express - node web framework</title>4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">5 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>6 <style>7 #tagline {8 margin-left: 75px;9 margin-bottom: 30px;10 color: rgba(255,255,255,0.7); }11 html {12 background: #1c1c1c url(images/bg.tile.jpg); }1314 body {15 margin: 0;16 padding-bottom: 30px;17 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";18 font-size: 14px;19 line-height: 1.5;20 -webkit-font-smoothing: antialiased;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, h4 {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; }50 h4 {51 margin-left: 10px;52 font-size: 14px;53 }5455 pre {56 margin: 20px 10px;57 padding: 25px 20px;58 background: rgba(0,0,0,0.5);59 border: 1px solid #323232;60 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);62 -webkit-border-radius: 5px;63 -moz-border-radius: 5px; }6465 code {66 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6768 ul {69 margin: 15px 0;70 padding: 0 0 0 35px; }71 ul li {72 margin: 0;73 padding: 2px 0;74 list-style: square; }75 ul li ul {76 margin: 0;77 padding-left: 12px;78 }7980 .man-name, #Express { display:none; }8182 .sect {83 margin-left: 40px; }84 img {85 margin-left: 20px;86 margin-bottom: 15px;87 }8889 #logo {90 display: block;91 margin-left: 30%;92 margin-bottom: 30px;93 width: 194px;94 height: 51px;95 background: url(images/logo.png) 0 0 no-repeat;96 text-indent: -99999px; }97 #logo:hover {98 opacity: 0.7; }99 #logo:active {100 opacity: 0.3; }101102 #ribbon {103 position: fixed;104 top: 0;105 right: 0;106 z-index: 2; }107108 #wrapper {109 width: 100%;110 min-height: 800px;111 background: url(images/top.png) 0 0 repeat-x; }112113 #container {114 margin: 0 auto;115 padding-top: 80px;116 width: 550px; }117118 #toc {119 position: fixed;120 top: 0;121 left: 0;122 margin: 0 0 0 15px;123 padding: 15px;124 height: 100%;125 background: rgba(0,0,0,0.2);126 overflow: auto;127 border-right: 1px solid rgba(255,255,255,0.05);128 }129 #toc li {130 padding: 0;131 list-style: none;132 }133 #toc li a {134 font-size: 11px;135 }136 #menu {137 margin-left: 75px;138 padding: 0;139 padding-bottom: 30px; }140 #menu li {141 display: inline;142 list-style: none; }143 #menu li a {144 display: block;145 float: left;146 margin: 0 2px;147 padding: 3px 15px;148 background: rgba(0,0,0,0.2);149 -webkit-border-radius: 8px;150 -moz-border-radius: 8px;151 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);153 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;154 -webkit-transition-duration: 0.15s;155 -webkit-transition-timing-function: ease-out; }156 #menu li a:hover,157 #menu li a.active {158 background: rgba(0,0,0,0.5); }159 #menu li a:active {160 background: rgba(0,0,0,0.1);161 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);162 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }163 </style>164 <script>165 $(function(){166 $('.section').hide();167 $('.toggle, a.section-title').toggle(function(){168 $(this).siblings('ul').fadeIn(300);169 return false;170 }, function(){171 $(this).siblings('ul').fadeOut(300);172 return false;173 });174 });175 </script>176 </head>177 <body>178 <a href='http://github.com/visionmedia/express'> 179 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 180 </a>181 <div id="wrapper">182 <div id="container">183 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 184 <p id="tagline">185 High performance, high class web development for186 <a href="http://nodejs.org">Node.js</a>187 </p>188 <ul id="menu">189 <li><a href="index.html">Home</a></li>190 <li><a href="guide.html">Guide</a></li>191 <li><a href="screencasts.html">Screencasts</a></li>192 <li><a href="applications.html">Applications</a></li>193 </ul>194<h3>Express 1.x to 2.x Migration</h3>195196<h3>HTTPS</h3>197198<p> Creating an HTTPS server is simply, simply pass the TLS options to <em>express.createServer()</em>:</p>199200<pre><code> var app = express.createServer({201 key: ...202 , cert: ...203 });204205 app.listen(443);206</code></pre>207208<h3>req.header() Referrer</h3>209210<p> Previously if anyone was doing something similar to:</p>211212<pre><code> req.headers.referrer || req.headers.referer213 req.header('Referrer') || req.header('Referer')214</code></pre>215216<p> With the new special-case we may now simply use <em>Referrer</em> which will return either if defined:</p>217218<pre><code> req.header('Referrer')219</code></pre>220221<h3>res.local(name, val)</h3>222223<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>224225<p> For example we may utilize this feature to create locals in middleware:</p>226227<pre><code> function loadUser(req, res, next) {228 User.get(req.params.id, function(err, user){229 res.local('user', user);230 next();231 });232 }233234 app.get('/user/:id', loadUser, function(req, res){235 res.render('user');236 });237</code></pre>238239<h3>req.param(name[, defaultValue])</h3>240241<p> Previously only <em>name</em> was accepted, so some of you may have been doing the following:</p>242243<pre><code> var id = req.param('id') || req.user.id;244</code></pre>245246<p> The new <em>defaultValue</em> argument can handle this nicely:</p>247248<pre><code> var id = req.param('id', req.user.id);249</code></pre>250251<h3>app.helpers() / app.locals()</h3>252253<p> <em>app.locals()</em> is now an alias of <em>app.helpers()</em>, as helpers makes more sense for functions.</p>254255<h3>req.accepts(type)</h3>256257<p> <em>req.accepts()</em> now accepts extensions:</p>258259<pre><code> // Accept: text/html260 req.accepts('html');261 req.accepts('.html');262 // =&gt; true263264 // Accept: text/*; application/json265 req.accepts('html');266 req.accepts('text/*');267 req.accepts('text/plain');268 req.accepts('application/json');269 // =&gt; true270271 req.accepts('image/png');272 req.accepts('png');273 // =&gt; false274</code></pre>275276<h3>res.cookie()</h3>277278<p> Previously only directly values could be passed, so for example:</p>279280<pre><code>res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000) });281</code></pre>282283<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>284285<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });286</code></pre>287288<h3>res.download() / res.sendfile()</h3>289290<p> Both of these methods now utilize Connect&rsquo;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>291292<pre><code> res.download('/path/to/file');293294 res.download('/path/to/file', function(err){295 if (err) {296 console.error(err);297 } else {298 console.log('transferred');299 }300 });301</code></pre>302303<p> The <em>stream threshold</em> setting was removed.</p>304305<h3>res.render()</h3>306307<p> Previously locals were passed as a separate key:</p>308309<pre><code> res.render('user', { layout: false, locals: { user: user }});310</code></pre>311312<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>313314<pre><code> res.render('user', { layout: false, user: user });315</code></pre>316317<h3>res.partial()</h3>318319<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>320321<pre><code> // render a collection of comments322 res.partial('comment', [comment1, comment2]); 323324 // render a single comment325 res.partial('comment', comment);326</code></pre>327328<h3>partial() locals</h3>329330<p> Both <em>res.partial()</em> and the <em>partial()</em> functions accept a 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>331332<pre><code> partial('user', { object: user, locals: { date: new Date }})333</code></pre>334335<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>336337<pre><code> partial('user', { locals: { user: user, date: new Date }})338</code></pre>339340<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>341342<pre><code> partial('user', { object: user, date: new Date })343</code></pre>344345<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>346347<pre><code> partial('user', { user: user, date: new Date })348</code></pre>349350<p> When a &ldquo;basic&rdquo; 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>351352<pre><code> partial('user', user); 353 partial('user', { object: user }); 354</code></pre>355356<h3>Template Engine Compliance</h3>357358<p> To comply with Express previously engines needed the following signature:</p>359360<pre><code> engine.render(str, options, function(err){});361</code></pre>362363<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>364365<pre><code> var fn = engine.compile(str, options);366 fn(locals);367</code></pre>368369<h3>View Partial Lookup</h3>370371<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>372373<h3>Mime Types</h3>374375<p> Express and Connect now utilize the <em>mime</em> module in npm, so to add more use:</p>376377<pre><code> require('mime').define({ 'foo/bar': ['foo', 'bar'] });378</code></pre>379380<h3>static() middleware</h3>381382<p> Previously named <code>staticProvider()</code>, the now <code>static()</code> middleware takes a single directory path, followed by options.</p>383384<pre><code> app.use(express.static(__dirname + '/public', { maxAge: oneYear }));385</code></pre>386387<p>Previously when using options the <code>root</code> option would be used for this:</p>388389<pre><code> app.use(express.staticProvider({ root: __dirname + '/public', maxAge: oneYear }));390</code></pre>391 </div>392 </div>393 </body>394</html>
deleted:docs/migrate.md-177 removed
12### Express 1.x to 2.x Migration34### HTTPS56 Creating an HTTPS server is simply, simply pass the TLS options to _express.createServer()_:7 8 var app = express.createServer({9 key: ...10 , cert: ...11 });1213 app.listen(443);1415### req.header() Referrer1617 Previously if anyone was doing something similar to:18 19 req.headers.referrer || req.headers.referer20 req.header('Referrer') || req.header('Referer')2122 With the new special-case we may now simply use _Referrer_ which will return either if defined:23 24 req.header('Referrer')2526### res.local(name, val)2728 Previously all local variables had to be passed to _res.render()_, or either _app.helpers()_ or _app.dynamicHelpers()_, now we may do this at the request-level progressively. The _res.local()_ method accepts a _name_ and _val_, however the locals passed to _res.render()_ will take precedence.2930 For example we may utilize this feature to create locals in middleware:3132 function loadUser(req, res, next) {33 User.get(req.params.id, function(err, user){34 res.local('user', user);35 next();36 });37 }3839 app.get('/user/:id', loadUser, function(req, res){40 res.render('user');41 });4243### req.param(name[, defaultValue])4445 Previously only _name_ was accepted, so some of you may have been doing the following:46 47 var id = req.param('id') || req.user.id;4849 The new _defaultValue_ argument can handle this nicely:50 51 var id = req.param('id', req.user.id);5253### app.helpers() / app.locals()5455 _app.locals()_ is now an alias of _app.helpers()_, as helpers makes more sense for functions.5657### req.accepts(type)5859 _req.accepts()_ now accepts extensions:60 61 62 // Accept: text/html63 req.accepts('html');64 req.accepts('.html');65 // => true66 67 // Accept: text/*; application/json68 req.accepts('html');69 req.accepts('text/*');70 req.accepts('text/plain');71 req.accepts('application/json');72 // => true73 74 req.accepts('image/png');75 req.accepts('png');76 // => false7778### res.cookie()7980 Previously only directly values could be passed, so for example:8182 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000) });8384However now we have the alternative _maxAge_ property which may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:8586 res.cookie('rememberme', 'yes', { maxAge: 900000 });8788### res.download() / res.sendfile()8990 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 _path_ and _stream_ were passed, however now only an _error_ is passed, when no error has occurred the callback will be invoked indicating that the file transfer is complete. The callback remains optional:91 92 res.download('/path/to/file');9394 res.download('/path/to/file', function(err){95 if (err) {96 console.error(err);97 } else {98 console.log('transferred');99 }100 });101102 The _stream threshold_ setting was removed.103104### res.render()105106 Previously locals were passed as a separate key:107 108 res.render('user', { layout: false, locals: { user: user }});109110 In Express 2.0 both the locals and the options are one in the same, meaning you cannot have a local variable named _layout_ as it is reserved for express, however this cleans up the API:111 112 res.render('user', { layout: false, user: user });113114### res.partial()115116 Express 2.0 adds the _res.partial()_ method, helpful for rendering partial fragments over WebSockets or Ajax requests etc. The API is identical to the _partial()_ calls within views.117 118 // render a collection of comments119 res.partial('comment', [comment1, comment2]); 120121 // render a single comment122 res.partial('comment', comment);123124### partial() locals125126 Both _res.partial()_ and the _partial()_ functions accept a single object consisting of both the options and the locals. Previously with Express 1.x you may pass _user_ to a partial, along with _date_ like so:127 128 partial('user', { object: user, locals: { date: new Date }})129130or perhaps if you preferred not to use the inferred name _user_ you may used a local for this as well:131132 partial('user', { locals: { user: user, date: new Date }})133134 With recent changes to Express 2.x the object passed is now both, so the following is valid for the _object_ option and locals:135 136 partial('user', { object: user, date: new Date })137138 Or the following which is equivalent, however the local var name is explicitly set to _user_ instead of deduced from the filename.139 140 partial('user', { user: user, date: new Date })141142 When a "basic" object aka _{}_ or _new Object_ is passed, it is considered options, otherwise it is considered the _object_. The following are equivalent:143 144 partial('user', user); 145 partial('user', { object: user }); 146147### Template Engine Compliance148149 To comply with Express previously engines needed the following signature:150 151 engine.render(str, options, function(err){});152153 Now they must export a _compile()_ 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.154 155 var fn = engine.compile(str, options);156 fn(locals);157158### View Partial Lookup159160 Previously partials were loaded relative to the now removed _view partials_ directory setting, or by default _views/partials_, now they are relative to the view calling them, read more on [view lookup](guide.html#view-lookup).161162### Mime Types163164 Express and Connect now utilize the _mime_ module in npm, so to add more use:165 166 require('mime').define({ 'foo/bar': ['foo', 'bar'] });167168### static() middleware169170 Previously named `staticProvider()`, the now `static()` middleware takes a single directory path, followed by options.171 172 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));173174Previously when using options the `root` option would be used for this:175176 app.use(express.staticProvider({ root: __dirname + '/public', maxAge: oneYear }));177
deleted:docs/screencasts.html-224 removed
1<html>2 <head>3 <title>Express - node web framework</title>4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">5 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>6 <style>7 #tagline {8 margin-left: 75px;9 margin-bottom: 30px;10 color: rgba(255,255,255,0.7); }11 html {12 background: #1c1c1c url(images/bg.tile.jpg); }1314 body {15 margin: 0;16 padding-bottom: 30px;17 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";18 font-size: 14px;19 line-height: 1.5;20 -webkit-font-smoothing: antialiased;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, h4 {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; }50 h4 {51 margin-left: 10px;52 font-size: 14px;53 }5455 pre {56 margin: 20px 10px;57 padding: 25px 20px;58 background: rgba(0,0,0,0.5);59 border: 1px solid #323232;60 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);62 -webkit-border-radius: 5px;63 -moz-border-radius: 5px; }6465 code {66 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6768 ul {69 margin: 15px 0;70 padding: 0 0 0 35px; }71 ul li {72 margin: 0;73 padding: 2px 0;74 list-style: square; }75 ul li ul {76 margin: 0;77 padding-left: 12px;78 }7980 .man-name, #Express { display:none; }8182 .sect {83 margin-left: 40px; }84 img {85 margin-left: 20px;86 margin-bottom: 15px;87 }8889 #logo {90 display: block;91 margin-left: 30%;92 margin-bottom: 30px;93 width: 194px;94 height: 51px;95 background: url(images/logo.png) 0 0 no-repeat;96 text-indent: -99999px; }97 #logo:hover {98 opacity: 0.7; }99 #logo:active {100 opacity: 0.3; }101102 #ribbon {103 position: fixed;104 top: 0;105 right: 0;106 z-index: 2; }107108 #wrapper {109 width: 100%;110 min-height: 800px;111 background: url(images/top.png) 0 0 repeat-x; }112113 #container {114 margin: 0 auto;115 padding-top: 80px;116 width: 550px; }117118 #toc {119 position: fixed;120 top: 0;121 left: 0;122 margin: 0 0 0 15px;123 padding: 15px;124 height: 100%;125 background: rgba(0,0,0,0.2);126 overflow: auto;127 border-right: 1px solid rgba(255,255,255,0.05);128 }129 #toc li {130 padding: 0;131 list-style: none;132 }133 #toc li a {134 font-size: 11px;135 }136 #menu {137 margin-left: 75px;138 padding: 0;139 padding-bottom: 30px; }140 #menu li {141 display: inline;142 list-style: none; }143 #menu li a {144 display: block;145 float: left;146 margin: 0 2px;147 padding: 3px 15px;148 background: rgba(0,0,0,0.2);149 -webkit-border-radius: 8px;150 -moz-border-radius: 8px;151 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);153 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;154 -webkit-transition-duration: 0.15s;155 -webkit-transition-timing-function: ease-out; }156 #menu li a:hover,157 #menu li a.active {158 background: rgba(0,0,0,0.5); }159 #menu li a:active {160 background: rgba(0,0,0,0.1);161 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);162 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }163 </style>164 <script>165 $(function(){166 $('.section').hide();167 $('.toggle, a.section-title').toggle(function(){168 $(this).siblings('ul').fadeIn(300);169 return false;170 }, function(){171 $(this).siblings('ul').fadeOut(300);172 return false;173 });174 });175 </script>176 </head>177 <body>178 <a href='http://github.com/visionmedia/express'> 179 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 180 </a>181 <div id="wrapper">182 <div id="container">183 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 184 <p id="tagline">185 High performance, high class web development for186 <a href="http://nodejs.org">Node.js</a>187 </p>188 <ul id="menu">189 <li><a href="index.html">Home</a></li>190 <li><a href="guide.html">Guide</a></li>191 <li><a href="screencasts.html">Screencasts</a></li>192 <li><a href="applications.html">Applications</a></li>193 </ul>194<h3>Introduction</h3>195196<p>This introduction screencast covers the basics of Express, and how to get started with your first application.</p>197198<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_1116090935.swf' /><param name='flashvars' value='i=139583' /><param name='allowFullScreen' value='true' /><embed src='http://screenr.com/Content/assets/screenr_1116090935.swf' flashvars='i=139583' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></object>199200201<h3>View Partials</h3>202203<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>204205<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_1116090935.swf' /><param name='flashvars' value='i=139591' /><param name='allowFullScreen' value='true' /><embed src='http://screenr.com/Content/assets/screenr_1116090935.swf' flashvars='i=139591' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></object>206207208<h3>Route Specific Middleware</h3>209210<p>In the screencast below we learn about the benefits of route-specific middleware.</p>211212<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_1116090935.swf' /><param name='flashvars' value='i=140296' /><param name='allowFullScreen' value='true' /><embed src='http://screenr.com/Content/assets/screenr_1116090935.swf' flashvars='i=140296' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></object>213214215<h3>Route Param Preconditions</h3>216217<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>218219<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_1116090935.swf' /><param name='flashvars' value='i=140300' /><param name='allowFullScreen' value='true' /><embed src='http://screenr.com/Content/assets/screenr_1116090935.swf' flashvars='i=140300' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></object>220221 </div>222 </div>223 </body>224</html>
deleted:docs/screencasts.md-24 removed