Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,866 lines · 39.5 KiB

Last changed by

Regenerated docsTj Holowaychukbefore adoptiond3abcaf

History of this file

Take it

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1–3why, one step back
1.\" generated with Ronn/v0.7.3
2.\" http://github.com/rtomayko/ronn/tree/0.7.33.

Added screencasts pageTj Holowaychukbefore adoption4144af3

line 4why, one step back
4.TH "GUIDE" "" "December 2010" "" ""

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 5–118why, one step back
5.
6.SH "NAME"7\fBguide\fR8.9.SS "Installation"10curl:11.12.IP "" 413.14.nf1516$ curl \-# http://expressjs\.com/install\.sh | sh17.18.fi19.20.IP "" 021.22.P23npm:24.25.IP "" 426.27.nf2829$ npm install express30.31.fi32.33.IP "" 034.35.SS "Creating An Application"36The \fIexpress\.Server\fR now inherits from \fIhttp\.Server\fR, however follows the same idiom by providing \fIexpress\.createServer()\fR as shown below\. This means that you can utilize Express server\'s transparently with other libraries\.37.38.IP "" 439.40.nf4142var app = require(\'express\')\.createServer();4344app\.get(\'/\', function(req, res){45 res\.send(\'hello world\');46});4748app\.listen(3000);49.50.fi51.52.IP "" 053.54.SS "Configuration"55Express supports arbitrary environments, such as \fIproduction\fR and \fIdevelopment\fR\. Developers can use the \fIconfigure()\fR method to setup needs required by the current environment\. When \fIconfigure()\fR is called without an environment name it will be run in \fIevery\fR environment prior to the environment specific callback\.56.57.P58In the example below we only \fIdumpExceptions\fR, and respond with exception stack traces in \fIdevelopment\fR mode, however for both environments we utilize \fImethodOverride\fR and \fIbodyDecoder\fR\. Note the use of \fIapp\.router\fR, which can (optionally) be used to mount the application routes, otherwise the first call to \fIapp\.{get,put,del,post}()\fR will mount the routes\.59.60.IP "" 461.62.nf6364app\.configure(function(){65 app\.use(express\.methodOverride());66 app\.use(express\.bodyDecoder());67 app\.use(app\.router);68 app\.use(express\.staticProvider(__dirname + \'/public\'));69});7071app\.configure(\'development\', function(){72 app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));73});7475app\.configure(\'production\', function(){76 app\.use(express\.errorHandler());77});78.79.fi80.81.IP "" 082.83.P84For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:85.86.IP "" 487.88.nf8990app\.configure(function(){91 app\.set(\'views\', __dirname + \'/views\');92 app\.set(\'views\');93 // => "\.\.\. views directory \.\.\."9495 app\.enable(\'some feature\');96 // same as app\.set(\'some feature\', true);9798 app\.disable(\'some feature\');99 // same as app\.set(\'some feature\', false);100});101.102.fi103.104.IP "" 0105.106.P107To alter the environment we can set the \fINODE_ENV\fR environment variable, for example:108.109.IP "" 4110.111.nf112113$ NODE_ENV=production node app\.js114.115.fi116.117.IP "" 0118.

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 119–121why, one step back
119.P
120This is \fIvery\fR important, as many caching mechanisms are \fIonly enabled\fR when in production\.121.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 122–173why, one step back
122.SS "Settings"
123Express supports the following settings out of the box:124.125.IP "\(bu" 4126\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR127.128.IP "\(bu" 4129\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.130.131.IP "\(bu" 4132\fIviews\fR Root views directory defaulting to \fBCWD/views\fR133.134.IP "\(bu" 4135\fIview engine\fR Default view engine name for views rendered without extensions136.137.IP "\(bu" 4138\fIview options\fR An object specifying global view options139.140.IP "\(bu" 4141\fIstream threshold\fR Bytesize indicating when a file should be streamed for \fIres\.sendfile()\fR using \fIfs\.ReadStream()\fR and \fIsys\.pump()\fR\.142.143.IP "" 0144.145.SS "Routing"146Express utilizes the HTTP verbs to provide a meaningful, expressive routing API\. For example we may want to render a user\'s account for the path \fI/user/12\fR, this can be done by defining the route below\. The values associated to the named placeholders are available as \fBreq\.params\fR\.147.148.IP "" 4149.150.nf151152app\.get(\'/user/:id\', function(req, res){153 res\.send(\'user \' + req\.params\.id);154});155.156.fi157.158.IP "" 0159.160.P161A route is simple a string which is compiled to a \fIRegExp\fR internally\. For example when \fI/user/:id\fR is compiled, a simplified version of the regexp may look similar to:162.163.IP "" 4164.165.nf166167\e/user\e/([^\e/]+)\e/?168.169.fi170.171.IP "" 0172.173.P

Regenerated docsTj Holowaychukbefore adoptiond3abcaf

line 174why, one step back
174Regular expression literals may also be passed for complex uses\. Since capture groups with literal \fIRegExp\fR\'s are anonymous we can access them directly \fBreq\.params\fR\. So our first capture group would be \fIreq\.params[0]\fR and the second would follow as \fIreq\.params[1]\fR\.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 175–241why, one step back
175.
176.IP "" 4177.178.nf179180app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){181 res\.send(req\.params);182});183.184.fi185.186.IP "" 0187.188.P189Curl requests against the previously defined route:190.191.IP "" 4192.193.nf194195 $ curl http://dev:3000/user196 [null,null]197 $ curl http://dev:3000/users198 [null,null]199 $ curl http://dev:3000/users/1200 ["1",null]201 $ curl http://dev:3000/users/1\.\.15202 ["1","15"]203.204.fi205.206.IP "" 0207.208.P209Below are some route examples, and the associated paths that they may consume:210.211.IP "" 4212.213.nf214215 "/user/:id"216 /user/12217218 "/users/:id?"219 /users/5220 /users221222 "/files/*"223 /files/jquery\.js224 /files/javascripts/jquery\.js225226 "/file/*\.*"227 /files/jquery\.js228 /files/javascripts/jquery\.js229230 "/user/:id/:operation?"231 /user/1232 /user/1/edit233234 "/products\.:format"235 /products\.json236 /products\.xml237238 "/products\.:format?"239 /products\.json240 /products\.xml241 /products

Regenerated docsTj Holowaychukbefore adoptiond3abcaf

lines 242–245why, one step back
242
243 "/user/:id\.:format?"244 /user/12245 /user/12\.json

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 246–250why, one step back
246.
247.fi248.249.IP "" 0250.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 251–271why, one step back
251.P
252For example we can \fBPOST\fR some json, and echo the json back using the \fIbodyDecoder\fR middleware which will parse json request bodies (as well as others), and place the result in \fIreq\.body\fR:253.254.IP "" 4255.256.nf257258var express = require(\'express\')259 , app = express\.createServer();260261app\.use(express\.bodyDecoder());262263app\.post(\'/\', function(req, res){264 res\.send(req\.body);265});266267app\.listen(3000);268.269.fi270.271.IP "" 0

Regenerated docsTj Holowaychukbefore adoptiond3abcaf

lines 272–274why, one step back
272.
273.P274Express 2\.0\.0\-pre also supports named capture groups\. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, however say for example we are limiting a user id to digits, we may use \fI\'/user/:id(\ed+)\'\fR which will \fInot\fR match unless the placeholder value contains only digits\.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

line 275why, one step back
275.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 276–299why, one step back
276.SS "Passing Route Control"
277We may pass control to the next \fImatching\fR route, by calling the \fIthird\fR argument, the \fInext()\fR function\. When a match cannot be made, control is passed back to Connect, and middleware continue to be invoked\. The same is true for several routes which have the same path defined, they will simply be executed in order until one does \fInot\fR call \fInext()\fR\.278.279.IP "" 4280.281.nf282283app\.get(\'/users/:id?\', function(req, res, next){284 var id = req\.params\.id;285 if (id) {286 // do something287 } else {288 next();289 }290});291292app\.get(\'/users\', function(req, res){293 // do something else294});295.296.fi297.298.IP "" 0299.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 300–342why, one step back
300.P
301Express 1\.0 also introduces the \fIall()\fR method, which provides a route callback matching any HTTP method\. This is useful in many ways, one example being the loading of resources before executing subsequent routes as shown below:302.303.IP "" 4304.305.nf306307var express = require(\'express\')308 , app = express\.createServer();309310var users = [{ name: \'tj\' }];311312app\.all(\'/user/:id/:op?\', function(req, res, next){313 req\.user = users[req\.params\.id];314 if (req\.user) {315 next();316 } else {317 next(new Error(\'cannot find user \' + req\.params\.id));318 }319});320321app\.get(\'/user/:id\', function(req, res){322 res\.send(\'viewing \' + req\.user\.name);323});324325app\.get(\'/user/:id/edit\', function(req, res){326 res\.send(\'editing \' + req\.user\.name);327});328329app\.put(\'/user/:id\', function(req, res){330 res\.send(\'updating \' + req\.user\.name);331});332333app\.get(\'*\', function(req, res){334 res\.send(\'what???\', 404);335});336337app\.listen(3000);338.339.fi340.341.IP "" 0342.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 343–412why, one step back
343.SS "Middleware"
344Middleware via Connect \fIhttp://github\.com/senchalabs/connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:345.346.IP "" 4347.348.nf349350 var express = require(\'express\');351352var app = express\.createServer(353 express\.logger(),354 express\.bodyDecoder()355 );356.357.fi358.359.IP "" 0360.361.P362Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:363.364.IP "" 4365.366.nf367368app\.use(express\.logger({ format: \':method :uri\' }));369.370.fi371.372.IP "" 0373.374.P375Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:376.377.IP "" 4378.379.nf380381var connect = require(\'connect\');382app\.use(connect\.logger());383.384.fi385.386.IP "" 0387.388.P389This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:390.391.IP "" 4392.393.nf394395app\.use(express\.logger());396.397.fi398.399.IP "" 0400.401.SS "Route Middleware"402Routes 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\.403.404.P405Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.406.407.IP "" 4408.409.nf410411app\.get(\'/user/:id\', function(req, res, next){412 loadUser(req\.params\.id, function(err, user){

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 413–414why, one step back
413 if (err) return next(err);
414 res\.send(\'Viewing user \' + user\.name);

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 415–456why, one step back
415 });
416});417.418.fi419.420.IP "" 0421.422.P423To 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\.424.425.IP "" 4426.427.nf428429function loadUser(req, res, next) {430 // You would fetch your user from the db431 var user = users[req\.params\.id];432 if (user) {433 req\.user = user;434 next();435 } else {436 next(new Error(\'Failed to load user \' + req\.params\.id));437 }438}439440app\.get(\'/user/:id\', loadUser, function(req, res){441 res\.send(\'Viewing user \' + req\.user\.name);442});443.444.fi445.446.IP "" 0447.448.P449Multiple 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\.450.451.IP "" 4452.453.nf454455function andRestrictToSelf(req, res, next) {456 req\.authenticatedUser\.id == req\.user\.id

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 457–458why, one step back
457 ? next()
458 : next(new Error(\'Unauthorized\'));

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 459–478why, one step back
459}
460461app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){462 res\.send(\'Editing user \' + req\.user\.name);463});464.465.fi466.467.IP "" 0468.469.P470Keeping in mind that middleware are simply functions, we can define function that \fIreturns\fR the middleware in order to create a more expressive and flexible solution as shown below\.471.472.IP "" 4473.474.nf475476function andRestrictTo(role) {477 return function(req, res, next) {478 req\.authenticatedUser\.role == role

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 479–480why, one step back
479 ? next()
480 : next(new Error(\'Unauthorized\'));

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 481–526why, one step back
481 }
482}483484app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){485 res\.send(\'Deleted user \' + req\.user\.name);486});487.488.fi489.490.IP "" 0491.492.P493Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.494.495.IP "" 4496.497.nf498499var a = [middleware1, middleware2]500 , b = [middleware3, middleware4]501 , all = [a, b];502503app\.get(\'/foo\', a, function(){});504app\.get(\'/bar\', a, function(){});505506app\.get(\'/\', a, middleware3, middleware4, function(){});507app\.get(\'/\', a, b, function(){});508app\.get(\'/\', all, function(){});509.510.fi511.512.IP "" 0513.514.P515For this example in full, view the route middleware example \fIhttp://github\.com/visionmedia/express/blob/master/examples/route\-middleware/app\.js\fR in the repository\.516.517.SS "HTTP Methods"518We have seen \fIapp\.get()\fR a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as \fIapp\.post()\fR, \fIapp\.del()\fR, etc\.519.520.P521A common example for \fIPOST\fR usage, is when "submitting" a form\. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it\.522.523.IP "" 4524.525.nf526

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 527–531why, one step back
527 <form method="post" action="/">
528 <input type="text" name="user[name]" />529 <input type="text" name="user[email]" />530 <input type="submit" value="Submit" />531 </form>

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 532–887why, one step back
532.
533.fi534.535.IP "" 0536.537.P538By default Express does not know what to do with this request body, so we should add the \fIbodyDecoder\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:539.540.IP "" 4541.542.nf543544app\.use(express\.bodyDecoder());545.546.fi547.548.IP "" 0549.550.P551Our route below will now have access to the \fIreq\.body\.user\fR object which will contain the \fIname\fR and \fIemail\fR properties when defined\.552.553.IP "" 4554.555.nf556557app\.post(\'/\', function(req, res){558 console\.log(req\.body\.user);559 res\.redirect(\'back\');560});561.562.fi563.564.IP "" 0565.566.P567When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyDecoder\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.568.569.IP "" 4570.571.nf572573app\.use(express\.bodyDecoder());574app\.use(express\.methodOverride());575.576.fi577.578.IP "" 0579.580.P581The reason that these are not always defaults, is simply because these are not required for Express to be fully functional\. Depending on the needs of your application, you may not need these at all, your methods such as \fIPUT\fR and \fIDELETE\fR can still be accessed by clients which can use them directly, although \fImethodOverride\fR provides a great solution for forms\. Below shows what the usage of \fIPUT\fR might look like:582.583.IP "" 4584.585.nf586587<form method="post" action="/">588 <input type="hidden" name="_method" value="put" />589 <input type="text" name="user[name]" />590 <input type="text" name="user[email]" />591 <input type="submit" value="Submit" />592</form>593594app\.put(\'/\', function(){595 console\.log(req\.body\.user);596 res\.redirect(\'back\');597});598.599.fi600.601.IP "" 0602.603.SS "Error Handling"604Express provides the \fIapp\.error()\fR method which receives exceptions thrown within a route, or passed to \fInext(err)\fR\. Below is an example which serves different pages based on our ad\-hoc \fINotFound\fR exception:605.606.IP "" 4607.608.nf609610function NotFound(msg){611 this\.name = \'NotFound\';612 Error\.call(this, msg);613 Error\.captureStackTrace(this, arguments\.callee);614}615616sys\.inherits(NotFound, Error);617618app\.get(\'/404\', function(req, res){619 throw new NotFound;620});621622app\.get(\'/500\', function(req, res){623 throw new Error(\'keyboard cat!\');624});625.626.fi627.628.IP "" 0629.630.P631We can call \fIapp\.error()\fR several times as shown below\. Here we check for an instanceof \fINotFound\fR and show the 404 page, or we pass on to the next error handler\.632.633.P634Note that these handlers can be defined anywhere, as they will be placed below the route handlers on \fIlisten()\fR\. This allows for definition within \fIconfigure()\fR blocks so we can handle exceptions in different ways based on the environment\.635.636.IP "" 4637.638.nf639640app\.error(function(err, req, res, next){641 if (err instanceof NotFound) {642 res\.render(\'404\.jade\');643 } else {644 next(err);645 }646});647.648.fi649.650.IP "" 0651.652.P653Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like654.655.IP "" 4656.657.nf658659app\.error(function(err, req, res){660 res\.render(\'500\.jade\', {661 locals: {662 error: err663 }664 });665});666.667.fi668.669.IP "" 0670.671.P672Our apps could also utilize the Connect \fIerrorHandler\fR middleware to report on exceptions\. For example if we wish to output exceptions in "development" mode to \fIstderr\fR we can use:673.674.IP "" 4675.676.nf677678app\.use(express\.errorHandler({ dumpExceptions: true }));679.680.fi681.682.IP "" 0683.684.P685Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:686.687.IP "" 4688.689.nf690691app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));692.693.fi694.695.IP "" 0696.697.P698The \fIerrorHandler\fR middleware also responds with \fIjson\fR if \fIAccept: application/json\fR is present, which is useful for developing apps that rely heavily on client\-side JavaScript\.699.700.SS "View Rendering"701View filenames take the form \fINAME\fR\.\fIENGINE\fR, where \fIENGINE\fR is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.render(str, options)\fR to comply with Express, however \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by jade\.702.703.P704Below is an example using Haml\.js \fIhttp://github\.com/visionmedia/haml\.js\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.html\fR will be passed as the \fIbody\fR local variable in \fIlayout\.haml\fR\.705.706.IP "" 4707.708.nf709710app\.get(\'/\', function(req, res){711 res\.render(\'index\.haml\', {712 locals: { title: \'My Site\' }713 });714});715.716.fi717.718.IP "" 0719.720.P721The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using Jade \fIhttp://github\.com/visionmedia/jade\fR we could set:722.723.IP "" 4724.725.nf726727app\.set(\'view engine\', \'jade\');728.729.fi730.731.IP "" 0732.733.P734Allowing us to render with:735.736.IP "" 4737.738.nf739740res\.render(\'index\');741.742.fi743.744.IP "" 0745.746.P747vs:748.749.IP "" 4750.751.nf752753res\.render(\'index\.jade\');754.755.fi756.757.IP "" 0758.759.P760When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:761.762.IP "" 4763.764.nf765766res\.render(\'another\-page\.ejs\');767.768.fi769.770.IP "" 0771.772.P773Express also provides the \fIview options\fR setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:774.775.IP "" 4776.777.nf778779app\.set(\'view options\', {780 layout: false781});782.783.fi784.785.IP "" 0786.787.P788Which can then be overridden within the \fBres\.render()\fR call if need be:789.790.IP "" 4791.792.nf793794res\.render(\'myview\.ejs\', { layout: true });795.796.fi797.798.IP "" 0799.800.P801When an alternate layout is required, we may also specify a path\. For example if we have \fIview engine\fR set to \fIjade\fR and a file named \fI\./views/mylayout\.jade\fR we can simply pass:802.803.IP "" 4804.805.nf806807res\.render(\'page\', { layout: \'mylayout\' });808.809.fi810.811.IP "" 0812.813.P814Otherwise we must specify the extension:815.816.IP "" 4817.818.nf819820res\.render(\'page\', { layout: \'mylayout\.jade\' });821.822.fi823.824.IP "" 0825.826.P827These paths may also be absolute:828.829.IP "" 4830.831.nf832833res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });834.835.fi836.837.IP "" 0838.839.P840A good example of this is specifying custom \fIejs\fR opening and closing tags:841.842.IP "" 4843.844.nf845846app\.set(\'view options\', {847 open: \'{{\',848 close: \'}}\'849});850.851.fi852.853.IP "" 0854.855.SS "View Partials"856The Express view system has built\-in support for partials and collections, which are sort of "mini" views representing a document fragment\. For example rather than iterating in a view to display comments, we would use a partial with collection support:857.858.IP "" 4859.860.nf861862partial(\'comment\.haml\', { collection: comments });863.864.fi865.866.IP "" 0867.868.P869To make things even less verbose we can assume the extension as \fI\.haml\fR when omitted, however if we wished we could use an ejs partial, within a haml view for example\.870.871.IP "" 4872.873.nf874875partial(\'comment\', { collection: comments });876.877.fi878.879.IP "" 0880.881.P882And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:883.884.IP "" 4885.886.nf887

Regenerated docsTj Holowaychukbefore adoption2a40cec

line 888why, one step back
888partial(\'comment\', comments);

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 889–905why, one step back
889.
890.fi891.892.IP "" 0893.894.P895When using the partial collection support a few "magic" variables are provided for free:896.897.IP "\(bu" 4898\fIfirstInCollection\fR True if this is the first object899.900.IP "\(bu" 4901\fIindexInCollection\fR Index of the object in the collection902.903.IP "\(bu" 4904\fIlastInCollection\fR True if this is the last object905.

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 906–908why, one step back
906.IP "\(bu" 4
907\fIcollectionLength\fR Length of the collection908.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 909–910why, one step back
909.IP "" 0
910.

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 911–913why, one step back
911.P
912For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.913.

Added screencasts pageTj Holowaychukbefore adoption4144af3

lines 914–916why, one step back
914.P
915NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead\. For example do \fInot\fR implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates\.916.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 917–928why, one step back
917.SS "Template Engines"
918Below are a few template engines commonly used with Express:919.920.IP "\(bu" 4921Jade \fIhttp://jade\-lang\.com\fR haml\.js successor922.923.IP "\(bu" 4924Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates925.926.IP "\(bu" 4927EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript928.

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 929–931why, one step back
929.IP "\(bu" 4
930CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating931.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 932–934why, one step back
932.IP "\(bu" 4
933jQuery Templates \fIhttps://github\.com/kof/node\-jqtpl\fR for node934.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 935–973why, one step back
935.IP "" 0
936.937.SS "Session Support"938Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieDecoder\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.939.940.IP "" 4941.942.nf943944app\.use(express\.cookieDecoder());945app\.use(express\.session());946.947.fi948.949.IP "" 0950.951.P952By default the \fIsession\fR middleware uses the memory store bundled with Connect, however many implementations exist\. For example connect\-redis \fIhttp://github\.com/visionmedia/connect\-redis\fR supplies a Redis \fIhttp://code\.google\.com/p/redis/\fR session store and can be used as shown below:953.954.IP "" 4955.956.nf957958var RedisStore = require(\'connect\-redis\');959app\.use(express\.cookieDecoder());960app\.use(express\.session({ store: new RedisStore }));961.962.fi963.964.IP "" 0965.966.P967Now the \fIreq\.session\fR and \fIreq\.sessionStore\fR properties will be accessible to all routes and subsequent middleware\. Properties on \fIreq\.session\fR are automatically saved on a response, so for example if we wish to shopping cart data:968.969.IP "" 4970.971.nf972973var RedisStore = require(\'connect\-redis\');

Regenerated docsTj Holowaychukbefore adoption1c9831a

line 974why, one step back
974app\.use(express\.bodyDecoder());

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 975–1002why, one step back
975app\.use(express\.cookieDecoder());
976app\.use(express\.session({ store: new RedisStore }));977978app\.post(\'/add\-to\-cart\', function(req, res){979 // Perhaps we posted several items with a form980 // (use the bodyDecoder() middleware for this)981 var items = req\.body\.items;982 req\.session\.items = items;983 res\.redirect(\'back\');984});985986app\.get(\'/add\-to\-cart\', function(req, res){987 // When redirected back to GET /add\-to\-cart988 // we could check req\.session\.items && req\.session\.items\.length989 // to print out a message990 if (req\.session\.items && req\.session\.items\.length) {991 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);992 }993 res\.render(\'shopping\-cart\');994});995.996.fi997.998.IP "" 0999.1000.P1001The \fIreq\.session\fR object also has methods such as \fISession#touch()\fR, \fISession#destroy()\fR, \fISession#regenerate()\fR among others to maintain and manipulate sessions\. For more information view the Connect Session \fIhttp://senchalabs\.github\.com/connect/session\.html\fR documentation\.1002.

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

lines 1003–1005why, one step back
1003.SS "Migration Guide"
1004Pre\-beta Express developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.1005.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1006–1049why, one step back
1006.SS "req\.header(key[, defaultValue])"
1007Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1008.1009.IP "" 41010.1011.nf10121013req\.header(\'Host\');1014req\.header(\'host\');1015req\.header(\'Accept\', \'*/*\');1016.1017.fi1018.1019.IP "" 01020.1021.SS "req\.accepts(type)"1022Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1023.1024.P1025When the \fIAccept\fR header is not present \fItrue\fR is returned\. Otherwise the given \fItype\fR is matched by an exact match, and then subtypes\. You may pass the subtype such as "html" which is then converted internally to "text/html" using the mime lookup table\.1026.1027.IP "" 41028.1029.nf10301031// Accept: text/html1032req\.accepts(\'html\');1033// => true10341035// Accept: text/*; application/json1036req\.accepts(\'html\');1037req\.accepts(\'text/html\');1038req\.accepts(\'text/plain\');1039req\.accepts(\'application/json\');1040// => true10411042req\.accepts(\'image/png\');1043req\.accepts(\'png\');1044// => false1045.1046.fi1047.1048.IP "" 01049.

Added req.is() docsTj Holowaychukbefore adoption806aefa

lines 1050–1107why, one step back
1050.SS "req\.is(type)"
1051Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.1052.1053.IP "" 41054.1055.nf10561057 // With Content\-Type: text/html; charset=utf\-81058 req\.is(\'html\');1059 req\.is(\'text/html\');1060 // => true10611062 // When Content\-Type is application/json1063 req\.is(\'json\');1064 req\.is(\'application/json\');1065 // => true10661067 req\.is(\'html\');1068 // => false1069.1070.fi1071.1072.IP "" 01073.1074.P1075Ad\-hoc callbacks can also be registered with Express, to perform assertions again the request, for example if we need an expressive way to check if our incoming request is an image, we can register \fI"an image"\fR callback:1076.1077.IP "" 41078.1079.nf10801081 app\.is(\'an image\', function(req){1082 return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1083 });1084.1085.fi1086.1087.IP "" 01088.1089.P1090Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1091.1092.IP "" 41093.1094.nf10951096 app\.post(\'/image/upload\', function(req, res, next){1097 if (req\.is(\'an image\')) {1098 // do something1099 } else {1100 next();1101 }1102 });1103.1104.fi1105.1106.IP "" 01107.

Merge branch 'is'Tj Holowaychukbefore adoption7a71380

lines 1108–1136why, one step back
1108.P
1109Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1110.1111.P1112Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1113.1114.IP "" 41115.1116.nf11171118req\.is(\'image/*\');1119.1120.fi1121.1122.IP "" 01123.1124.P1125We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1126.1127.IP "" 41128.1129.nf11301131req\.is(\'*/json\');1132.1133.fi1134.1135.IP "" 01136.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1137–1337why, one step back
1137.SS "req\.param(name)"
1138Return the value of param \fIname\fR when present\.1139.1140.IP "\(bu" 41141Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1142.1143.IP "\(bu" 41144Checks query string params (\fIreq\.query\fR), ex: ?id=121145.1146.IP "\(bu" 41147Checks urlencoded body params (\fIreq\.body\fR), ex: id=121148.1149.IP "" 01150.1151.P1152To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.1153.1154.SS "req\.flash(type[, msg])"1155Queue flash \fImsg\fR of the given \fItype\fR\.1156.1157.IP "" 41158.1159.nf11601161req\.flash(\'info\', \'email sent\');1162req\.flash(\'error\', \'email delivery failed\');1163req\.flash(\'info\', \'email re\-sent\');1164// => 211651166req\.flash(\'info\');1167// => [\'email sent\', \'email re\-sent\']11681169req\.flash(\'info\');1170// => []11711172req\.flash();1173// => { error: [\'email delivery failed\'], info: [] }1174.1175.fi1176.1177.IP "" 01178.1179.P1180Flash notification message may also utilize formatters, by default only the %s string formatter is available:1181.1182.IP "" 41183.1184.nf11851186req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1187.1188.fi1189.1190.IP "" 01191.1192.SS "req\.isXMLHttpRequest"1193Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1194.1195.IP "" 41196.1197.nf11981199req\.xhr1200req\.isXMLHttpRequest1201.1202.fi1203.1204.IP "" 01205.1206.SS "res\.header(key[, val])"1207Get or set the response header \fIkey\fR\.1208.1209.IP "" 41210.1211.nf12121213res\.header(\'Content\-Length\');1214// => undefined12151216res\.header(\'Content\-Length\', 123);1217// => 12312181219res\.header(\'Content\-Length\');1220// => 1231221.1222.fi1223.1224.IP "" 01225.1226.SS "res\.contentType(type)"1227Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1228.1229.IP "" 41230.1231.nf12321233 var filename = \'path/to/image\.png\';1234 res\.contentType(filename);1235 // res\.headers[\'Content\-Type\'] is now "image/png"1236.1237.fi1238.1239.IP "" 01240.1241.SS "res\.attachment([filename])"1242Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1243.1244.IP "" 41245.1246.nf12471248 res\.attachment(\'path/to/my/image\.png\');1249.1250.fi1251.1252.IP "" 01253.1254.SS "res\.sendfile(path)"1255Used by \fBres\.download()\fR to transfer an arbitrary file\.1256.1257.IP "" 41258.1259.nf12601261res\.sendfile(\'path/to/my\.file\');1262.1263.fi1264.1265.IP "" 01266.1267.P1268This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed\. When a callback is not given, and the file has \fBnot\fR been streamed, \fInext(err)\fR will be called on an exception\.1269.1270.IP "" 41271.1272.nf12731274res\.sendfile(path, function(err, path){1275 if (err) {1276 // handle the error1277 } else {1278 console\.log(\'transferred %s\', path);1279 }1280});1281.1282.fi1283.1284.IP "" 01285.1286.P1287When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.1288.1289.SS "res\.download(file[, filename])"1290Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1291.1292.IP "" 41293.1294.nf12951296res\.download(\'path/to/image\.png\');1297res\.download(\'path/to/image\.png\', \'foo\.png\');1298.1299.fi1300.1301.IP "" 01302.1303.P1304This is equivalent to:1305.1306.IP "" 41307.1308.nf13091310res\.attachment(file);1311res\.sendfile(file);1312.1313.fi1314.1315.IP "" 01316.1317.SS "res\.send(body|status[, headers|status[, status]])"1318The \fBres\.send()\fR method is a high level response utility allowing you to pass objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status code based responses\. The following are all valid uses:1319.1320.IP "" 41321.1322.nf13231324 res\.send(); // 2041325 res\.send(new Buffer(\'wahoo\'));1326 res\.send({ some: \'json\' });1327 res\.send(\'<p>some html</p>\');1328 res\.send(\'Sorry, cant find that\', 404);1329 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1330 res\.send(404);1331.1332.fi1333.1334.IP "" 01335.1336.P1337By default the \fIContent\-Type\fR response header is set, however if explicitly assigned through \fBres\.send()\fR or previously with \fBres\.header()\fR or \fBres\.contentType()\fR it will not be set again\.

Added screencasts pageTj Holowaychukbefore adoption4144af3

lines 1338–1340why, one step back
1338.
1339.P1340Note that this method \fIend()\fR the response, so you will want to use node\'s \fIres\.writeHead()\fR / \fIres\.write()\fR for multiple writes or streaming\.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1341–1432why, one step back
1341.
1342.SS "res\.redirect(url[, status])"1343Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1344.1345.IP "" 41346.1347.nf13481349res\.redirect(\'/\', 301);1350res\.redirect(\'/account\');1351res\.redirect(\'http://google\.com\');1352res\.redirect(\'home\');1353res\.redirect(\'back\');1354.1355.fi1356.1357.IP "" 01358.1359.P1360Express supports "redirect mapping", which by default provides \fIhome\fR, and \fIback\fR\. The \fIback\fR map checks the \fIReferrer\fR and \fIReferer\fR headers, while \fIhome\fR utilizes the "home" setting and defaults to "/"\.1361.1362.SS "res\.cookie(name, val[, options])"1363Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1364.1365.IP "" 41366.1367.nf13681369// "Remember me" for 15 minutes1370res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1371.1372.fi1373.1374.IP "" 01375.1376.P1377To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1378.1379.IP "" 41380.1381.nf13821383app\.use(express\.cookieDecoder());13841385app\.get(\'/\', function(req, res){1386 // use req\.cookies\.rememberme1387});1388.1389.fi1390.1391.IP "" 01392.1393.SS "res\.clearCookie(name)"1394Clear cookie \fIname\fR by setting "expires" far in the past\.1395.1396.IP "" 41397.1398.nf13991400res\.clearCookie(\'rememberme\');1401.1402.fi1403.1404.IP "" 01405.1406.SS "res\.render(view[, options[, fn]])"1407Render \fIview\fR with the given \fIoptions\fR and optional callback \fIfn\fR\. When a callback function is given a response will \fInot\fR be made automatically, however otherwise a response of \fI200\fR and \fItext/html\fR is given\.1408.1409.P1410Most engines accept one or more of the following options, both haml \fIhttp://github\.com/visionmedia/haml\.js\fR and jade \fIhttp://github\.com/visionmedia/jade\fR accept all:1411.1412.IP "\(bu" 41413\fIscope\fR Template evaluation context (value of \fIthis\fR)1414.1415.IP "\(bu" 41416\fIlocals\fR Object containing local variables1417.1418.IP "\(bu" 41419\fIdebug\fR Output debugging information1420.1421.IP "\(bu" 41422\fIstatus\fR Response status code, defaults to 2001423.1424.IP "\(bu" 41425\fIheaders\fR Response headers object1426.1427.IP "" 01428.1429.SS "res\.partial(view[, options])"1430Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1431.1432.IP "\(bu" 4

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

line 1433why, one step back
1433\fIobject\fR the object named by \fIas\fR or derived from the view name

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1434–1435why, one step back
1434.
1435.IP "\(bu" 4

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 1436–1438why, one step back
1436\fIas\fR Variable name for each \fIcollection\fR or \fIobject\fR value, defaults to the view name\.
1437.1438.IP "\(bu" 4

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1439–1461why, one step back
1439as: \'something\' will add the \fIsomething\fR local variable
1440.1441.IP "\(bu" 41442as: this will use the collection value as the template context1443.1444.IP "\(bu" 41445as: global will merge the collection value\'s properties with \fIlocals\fR1446.1447.IP "" 014481449.1450.IP "\(bu" 41451\fIcollection\fR Array of objects, the name is derived from the view name itself\. For example \fIvideo\.html\fR will have a object \fIvideo\fR available to it\.1452.1453.IP "" 01454.1455.P1456The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1457.1458.IP "" 41459.1460.nf1461

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 1462–1463why, one step back
1462partial(\'theatre/movie\.jade\', { collection: movies });
1463partial(\'theatre/movie\.jade\', movies);

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1464–1507why, one step back
1464partial(\'movie\.jade\', { collection: movies });
1465partial(\'movie\.jade\', movies);1466partial(\'movie\', movies);1467// In view: movie\.director1468.1469.fi1470.1471.IP "" 01472.1473.P1474To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1475.1476.IP "" 41477.1478.nf14791480partial(\'movie\', { collection: movies, as: \'video\' });1481// In view: video\.director1482.1483.fi1484.1485.IP "" 01486.1487.P1488Also we can make our movie the value of \fIthis\fR within our view so that instead of \fImovie\.director\fR we could use \fIthis\.director\fR\.1489.1490.IP "" 41491.1492.nf14931494partial(\'movie\', { collection: movies, as: this });1495// In view: this\.director1496.1497.fi1498.1499.IP "" 01500.1501.P1502Another alternative is to "explode" the properties of the collection item into pseudo globals (local variables) by using \fIas: global\fR, which again is syntactic sugar:1503.1504.IP "" 41505.1506.nf1507

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

line 1508why, one step back
1508partial(\'movie\', { collection: movies, as: global });

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1509–1514why, one step back
1509// In view: director
1510.1511.fi1512.1513.IP "" 01514.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 1515–1551why, one step back
1515.P
1516This same logic applies to a single partial object usage:1517.1518.IP "" 41519.1520.nf15211522partial(\'movie\', { object: movie, as: this });1523// In view: this\.director15241525partial(\'movie\', { object: movie, as: global });1526// In view: director15271528partial(\'movie\', { object: movie, as: \'video\' });1529// In view: video\.director15301531partial(\'movie\', { object: movie });1532// In view: movie\.director1533.1534.fi1535.1536.IP "" 01537.1538.P1539When a non\-collection (does \fInot\fR have \fI\.length\fR) is passed as the second argument, it is assumed to be the \fIobject\fR, after which the object\'s local variable name is derived from the view name:1540.1541.IP "" 41542.1543.nf15441545partial(\'movie\', movie);1546// => In view: movie\.director1547.1548.fi1549.1550.IP "" 01551.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1552–1560why, one step back
1552.SS "app\.set(name[, val])"
1553Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1554.1555.IP "" 41556.1557.nf15581559app\.set(\'views\', __dirname + \'/views\');1560app\.set(\'views\');

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 1561–1574why, one step back
1561// => \.\.\.path\.\.\.
1562.1563.fi1564.1565.IP "" 01566.1567.P1568Alternatively you may simply access the settings via \fIapp\.settings\fR:1569.1570.IP "" 41571.1572.nf15731574app\.settings\.views

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1575–1810why, one step back
1575// => \.\.\.path\.\.\.
1576.1577.fi1578.1579.IP "" 01580.1581.SS "app\.enable(name)"1582Enable the given setting \fIname\fR:1583.1584.IP "" 41585.1586.nf15871588app\.enable(\'some arbitrary setting\');1589app\.set(\'some arbitrary setting\');1590// => true1591.1592.fi1593.1594.IP "" 01595.1596.SS "app\.disable(name)"1597Disable the given setting \fIname\fR:1598.1599.IP "" 41600.1601.nf16021603app\.disable(\'some setting\');1604app\.set(\'some setting\');1605// => false1606.1607.fi1608.1609.IP "" 01610.1611.SS "app\.configure(env|function[, function])"1612Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1613.1614.IP "" 41615.1616.nf16171618app\.configure(function(){1619 // executed for each env1620});16211622app\.configure(\'development\', function(){1623 // executed for \'development\' only1624});1625.1626.fi1627.1628.IP "" 01629.1630.SS "app\.redirect(name, val)"1631For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1632.1633.IP "" 41634.1635.nf16361637app\.redirect(\'google\', \'http://google\.com\');1638.1639.fi1640.1641.IP "" 01642.1643.P1644Now in a route we may call:1645.1646.P1647res\.redirect(\'google\');1648.1649.P1650We may also map dynamic redirects:1651.1652.IP "" 41653.1654.nf16551656app\.redirect(\'comments\', function(req, res){1657 return \'/post/\' + req\.params\.id + \'/comments\';1658});1659.1660.fi1661.1662.IP "" 01663.1664.P1665So now we may do the following, and the redirect will dynamically adjust to the context of the request\. If we called this route with \fIGET /post/12\fR our redirect \fILocation\fR would be \fI/post/12/comments\fR\.1666.1667.IP "" 41668.1669.nf16701671app\.get(\'/post/:id\', function(req, res){1672 res\.redirect(\'comments\');1673});1674.1675.fi1676.1677.IP "" 01678.1679.SS "app\.error(function)"1680Adds an error handler \fIfunction\fR which will receive the exception as the first parameter as shown below\. Note that we may set several error handlers by making several calls to this method, however the handler should call \fInext(err)\fR if it does not wish to deal with the exception:1681.1682.IP "" 41683.1684.nf16851686app\.error(function(err, req, res, next){1687 res\.send(err\.message, 500);1688});1689.1690.fi1691.1692.IP "" 01693.1694.SS "app\.helpers(obj)"1695Registers static view helpers\.1696.1697.IP "" 41698.1699.nf17001701app\.helpers({1702 name: function(first, last){ return first + \', \' + last },1703 firstName: \'tj\',1704 lastName: \'holowaychuk\'1705});1706.1707.fi1708.1709.IP "" 01710.1711.P1712Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1713.1714.IP "" 41715.1716.nf17171718<%= name(firstName, lastName) %>1719.1720.fi1721.1722.IP "" 01723.1724.SS "app\.dynamicHelpers(obj)"1725Registers dynamic view helpers\. Dynamic view helpers are simply functions which accept \fIreq\fR, \fIres\fR, and are evaluated against the \fIServer\fR instance before a view is rendered\. The \fIreturn value\fR of this function becomes the local variable it is associated with\.1726.1727.IP "" 41728.1729.nf17301731app\.dynamicHelpers({1732 session: function(req, res){1733 return req\.session;1734 }1735});1736.1737.fi1738.1739.IP "" 01740.1741.P1742All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1743.1744.IP "" 41745.1746.nf17471748<%= session\.name %>1749.1750.fi1751.1752.IP "" 01753.1754.SS "app\.mounted(fn)"1755Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1756.1757.IP "" 41758.1759.nf17601761var app = express\.createServer(),1762 blog = express\.createServer();17631764blog\.mounted(function(parent){1765 // parent is app1766 // "this" is blog1767});17681769app\.use(blog);1770.1771.fi1772.1773.IP "" 01774.1775.SS "app\.register(ext, exports)"1776Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:1777.1778.IP "" 41779.1780.nf17811782 app\.register(\'\.html\', require(\'jade\'));1783.1784.fi1785.1786.IP "" 01787.1788.P1789This is also useful for libraries that may not match extensions correctly\. For example my haml\.js library is installed from npm as "hamljs" so instead of layout\.hamljs, we can register the engine as "\.haml":1790.1791.IP "" 41792.1793.nf17941795 app\.register(\'\.haml\', require(\'haml\-js\'));1796.1797.fi1798.1799.IP "" 01800.1801.P1802For engines that do not comply with the Express specification, we can also wrap their api this way\.1803.1804.IP "" 41805.1806.nf18071808 app\.register(\'\.foo\', {1809 render: function(str, options) {1810 // perhaps their api is

Regenerated docsTj Holowaychukbefore adoption5152823

line 1811why, one step back
1811 // return foo\.toHTML(str, options);

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1812–1866why, one step back
1812 }
1813 });1814.1815.fi1816.1817.IP "" 01818.1819.SS "app\.listen([port[, host]])"1820Bind the app server to the given \fIport\fR, which defaults to 3000\. When \fIhost\fR is omitted all connections will be accepted via \fIINADDR_ANY\fR\.1821.1822.IP "" 41823.1824.nf18251826app\.listen();1827app\.listen(3000);1828app\.listen(3000, \'n\.n\.n\.n\');1829.1830.fi1831.1832.IP "" 01833.1834.P1835The \fIport\fR argument may also be a string representing the path to a unix domain socket:1836.1837.IP "" 41838.1839.nf18401841app\.listen(\'/tmp/express\.sock\');1842.1843.fi1844.1845.IP "" 01846.1847.P1848Then try it out:1849.1850.IP "" 41851.1852.nf18531854$ telnet /tmp/express\.sock1855GET / HTTP/1\.118561857HTTP/1\.1 200 OK1858Content\-Type: text/plain1859Content\-Length: 1118601861Hello World1862.1863.fi1864.1865.IP "" 01866