Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,859 lines · 39.1 KiB

Last changed by

Added screencasts pageTj Holowaychukbefore adoption4144af3

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–246why, 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.P174Regular 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\.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 /products242.243.fi244.245.IP "" 0246.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 247–268why, one step back
247.P
248For 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:249.250.IP "" 4251.252.nf253254var express = require(\'express\')255 , app = express\.createServer();256257app\.use(express\.bodyDecoder());258259app\.post(\'/\', function(req, res){260 res\.send(req\.body);261});262263app\.listen(3000);264.265.fi266.267.IP "" 0268.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 269–292why, one step back
269.SS "Passing Route Control"
270We 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\.271.272.IP "" 4273.274.nf275276app\.get(\'/users/:id?\', function(req, res, next){277 var id = req\.params\.id;278 if (id) {279 // do something280 } else {281 next();282 }283});284285app\.get(\'/users\', function(req, res){286 // do something else287});288.289.fi290.291.IP "" 0292.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 293–335why, one step back
293.P
294Express 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:295.296.IP "" 4297.298.nf299300var express = require(\'express\')301 , app = express\.createServer();302303var users = [{ name: \'tj\' }];304305app\.all(\'/user/:id/:op?\', function(req, res, next){306 req\.user = users[req\.params\.id];307 if (req\.user) {308 next();309 } else {310 next(new Error(\'cannot find user \' + req\.params\.id));311 }312});313314app\.get(\'/user/:id\', function(req, res){315 res\.send(\'viewing \' + req\.user\.name);316});317318app\.get(\'/user/:id/edit\', function(req, res){319 res\.send(\'editing \' + req\.user\.name);320});321322app\.put(\'/user/:id\', function(req, res){323 res\.send(\'updating \' + req\.user\.name);324});325326app\.get(\'*\', function(req, res){327 res\.send(\'what???\', 404);328});329330app\.listen(3000);331.332.fi333.334.IP "" 0335.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 336–405why, one step back
336.SS "Middleware"
337Middleware 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:338.339.IP "" 4340.341.nf342343 var express = require(\'express\');344345var app = express\.createServer(346 express\.logger(),347 express\.bodyDecoder()348 );349.350.fi351.352.IP "" 0353.354.P355Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:356.357.IP "" 4358.359.nf360361app\.use(express\.logger({ format: \':method :uri\' }));362.363.fi364.365.IP "" 0366.367.P368Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:369.370.IP "" 4371.372.nf373374var connect = require(\'connect\');375app\.use(connect\.logger());376.377.fi378.379.IP "" 0380.381.P382This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:383.384.IP "" 4385.386.nf387388app\.use(express\.logger());389.390.fi391.392.IP "" 0393.394.SS "Route Middleware"395Routes 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\.396.397.P398Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.399.400.IP "" 4401.402.nf403404app\.get(\'/user/:id\', function(req, res, next){405 loadUser(req\.params\.id, function(err, user){

Regenerated guideTj Holowaychukbefore adoptionab3337d

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 408–449why, one step back
408 });
409});410.411.fi412.413.IP "" 0414.415.P416To 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\.417.418.IP "" 4419.420.nf421422function loadUser(req, res, next) {423 // You would fetch your user from the db424 var user = users[req\.params\.id];425 if (user) {426 req\.user = user;427 next();428 } else {429 next(new Error(\'Failed to load user \' + req\.params\.id));430 }431}432433app\.get(\'/user/:id\', loadUser, function(req, res){434 res\.send(\'Viewing user \' + req\.user\.name);435});436.437.fi438.439.IP "" 0440.441.P442Multiple 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\.443.444.IP "" 4445.446.nf447448function andRestrictToSelf(req, res, next) {449 req\.authenticatedUser\.id == req\.user\.id

Regenerated guideTj Holowaychukbefore adoptionab3337d

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 452–471why, one step back
452}
453454app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){455 res\.send(\'Editing user \' + req\.user\.name);456});457.458.fi459.460.IP "" 0461.462.P463Keeping 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\.464.465.IP "" 4466.467.nf468469function andRestrictTo(role) {470 return function(req, res, next) {471 req\.authenticatedUser\.role == role

Regenerated guideTj Holowaychukbefore adoptionab3337d

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 474–519why, one step back
474 }
475}476477app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){478 res\.send(\'Deleted user \' + req\.user\.name);479});480.481.fi482.483.IP "" 0484.485.P486Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.487.488.IP "" 4489.490.nf491492var a = [middleware1, middleware2]493 , b = [middleware3, middleware4]494 , all = [a, b];495496app\.get(\'/foo\', a, function(){});497app\.get(\'/bar\', a, function(){});498499app\.get(\'/\', a, middleware3, middleware4, function(){});500app\.get(\'/\', a, b, function(){});501app\.get(\'/\', all, function(){});502.503.fi504.505.IP "" 0506.507.P508For 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\.509.510.SS "HTTP Methods"511We 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\.512.513.P514A 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\.515.516.IP "" 4517.518.nf519

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 520–524why, one step back
520 <form method="post" action="/">
521 <input type="text" name="user[name]" />522 <input type="text" name="user[email]" />523 <input type="submit" value="Submit" />524 </form>

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 525–880why, one step back
525.
526.fi527.528.IP "" 0529.530.P531By 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:532.533.IP "" 4534.535.nf536537app\.use(express\.bodyDecoder());538.539.fi540.541.IP "" 0542.543.P544Our 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\.545.546.IP "" 4547.548.nf549550app\.post(\'/\', function(req, res){551 console\.log(req\.body\.user);552 res\.redirect(\'back\');553});554.555.fi556.557.IP "" 0558.559.P560When 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\.561.562.IP "" 4563.564.nf565566app\.use(express\.bodyDecoder());567app\.use(express\.methodOverride());568.569.fi570.571.IP "" 0572.573.P574The 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:575.576.IP "" 4577.578.nf579580<form method="post" action="/">581 <input type="hidden" name="_method" value="put" />582 <input type="text" name="user[name]" />583 <input type="text" name="user[email]" />584 <input type="submit" value="Submit" />585</form>586587app\.put(\'/\', function(){588 console\.log(req\.body\.user);589 res\.redirect(\'back\');590});591.592.fi593.594.IP "" 0595.596.SS "Error Handling"597Express 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:598.599.IP "" 4600.601.nf602603function NotFound(msg){604 this\.name = \'NotFound\';605 Error\.call(this, msg);606 Error\.captureStackTrace(this, arguments\.callee);607}608609sys\.inherits(NotFound, Error);610611app\.get(\'/404\', function(req, res){612 throw new NotFound;613});614615app\.get(\'/500\', function(req, res){616 throw new Error(\'keyboard cat!\');617});618.619.fi620.621.IP "" 0622.623.P624We 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\.625.626.P627Note 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\.628.629.IP "" 4630.631.nf632633app\.error(function(err, req, res, next){634 if (err instanceof NotFound) {635 res\.render(\'404\.jade\');636 } else {637 next(err);638 }639});640.641.fi642.643.IP "" 0644.645.P646Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like647.648.IP "" 4649.650.nf651652app\.error(function(err, req, res){653 res\.render(\'500\.jade\', {654 locals: {655 error: err656 }657 });658});659.660.fi661.662.IP "" 0663.664.P665Our 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:666.667.IP "" 4668.669.nf670671app\.use(express\.errorHandler({ dumpExceptions: true }));672.673.fi674.675.IP "" 0676.677.P678Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:679.680.IP "" 4681.682.nf683684app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));685.686.fi687.688.IP "" 0689.690.P691The \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\.692.693.SS "View Rendering"694View 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\.695.696.P697Below 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\.698.699.IP "" 4700.701.nf702703app\.get(\'/\', function(req, res){704 res\.render(\'index\.haml\', {705 locals: { title: \'My Site\' }706 });707});708.709.fi710.711.IP "" 0712.713.P714The 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:715.716.IP "" 4717.718.nf719720app\.set(\'view engine\', \'jade\');721.722.fi723.724.IP "" 0725.726.P727Allowing us to render with:728.729.IP "" 4730.731.nf732733res\.render(\'index\');734.735.fi736.737.IP "" 0738.739.P740vs:741.742.IP "" 4743.744.nf745746res\.render(\'index\.jade\');747.748.fi749.750.IP "" 0751.752.P753When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:754.755.IP "" 4756.757.nf758759res\.render(\'another\-page\.ejs\');760.761.fi762.763.IP "" 0764.765.P766Express 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:767.768.IP "" 4769.770.nf771772app\.set(\'view options\', {773 layout: false774});775.776.fi777.778.IP "" 0779.780.P781Which can then be overridden within the \fBres\.render()\fR call if need be:782.783.IP "" 4784.785.nf786787res\.render(\'myview\.ejs\', { layout: true });788.789.fi790.791.IP "" 0792.793.P794When 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:795.796.IP "" 4797.798.nf799800res\.render(\'page\', { layout: \'mylayout\' });801.802.fi803.804.IP "" 0805.806.P807Otherwise we must specify the extension:808.809.IP "" 4810.811.nf812813res\.render(\'page\', { layout: \'mylayout\.jade\' });814.815.fi816.817.IP "" 0818.819.P820These paths may also be absolute:821.822.IP "" 4823.824.nf825826res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });827.828.fi829.830.IP "" 0831.832.P833A good example of this is specifying custom \fIejs\fR opening and closing tags:834.835.IP "" 4836.837.nf838839app\.set(\'view options\', {840 open: \'{{\',841 close: \'}}\'842});843.844.fi845.846.IP "" 0847.848.SS "View Partials"849The 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:850.851.IP "" 4852.853.nf854855partial(\'comment\.haml\', { collection: comments });856.857.fi858.859.IP "" 0860.861.P862To 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\.863.864.IP "" 4865.866.nf867868partial(\'comment\', { collection: comments });869.870.fi871.872.IP "" 0873.874.P875And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:876.877.IP "" 4878.879.nf880

Regenerated docsTj Holowaychukbefore adoption2a40cec

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 882–898why, one step back
882.
883.fi884.885.IP "" 0886.887.P888When using the partial collection support a few "magic" variables are provided for free:889.890.IP "\(bu" 4891\fIfirstInCollection\fR True if this is the first object892.893.IP "\(bu" 4894\fIindexInCollection\fR Index of the object in the collection895.896.IP "\(bu" 4897\fIlastInCollection\fR True if this is the last object898.

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 899–901why, one step back
899.IP "\(bu" 4
900\fIcollectionLength\fR Length of the collection901.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 902–903why, one step back
902.IP "" 0
903.

Regenerated docsTj Holowaychukbefore adoption2a40cec

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

Added screencasts pageTj Holowaychukbefore adoption4144af3

lines 907–909why, one step back
907.P
908NOTE: 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\.909.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 910–921why, one step back
910.SS "Template Engines"
911Below are a few template engines commonly used with Express:912.913.IP "\(bu" 4914Jade \fIhttp://jade\-lang\.com\fR haml\.js successor915.916.IP "\(bu" 4917Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates918.919.IP "\(bu" 4920EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript921.

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 922–924why, one step back
922.IP "\(bu" 4
923CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating924.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 925–927why, one step back
925.IP "\(bu" 4
926jQuery Templates \fIhttps://github\.com/kof/node\-jqtpl\fR for node927.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 928–966why, one step back
928.IP "" 0
929.930.SS "Session Support"931Sessions 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\.932.933.IP "" 4934.935.nf936937app\.use(express\.cookieDecoder());938app\.use(express\.session());939.940.fi941.942.IP "" 0943.944.P945By 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:946.947.IP "" 4948.949.nf950951var RedisStore = require(\'connect\-redis\');952app\.use(express\.cookieDecoder());953app\.use(express\.session({ store: new RedisStore }));954.955.fi956.957.IP "" 0958.959.P960Now 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:961.962.IP "" 4963.964.nf965966var RedisStore = require(\'connect\-redis\');

Regenerated docsTj Holowaychukbefore adoption1c9831a

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 968–995why, one step back
968app\.use(express\.cookieDecoder());
969app\.use(express\.session({ store: new RedisStore }));970971app\.post(\'/add\-to\-cart\', function(req, res){972 // Perhaps we posted several items with a form973 // (use the bodyDecoder() middleware for this)974 var items = req\.body\.items;975 req\.session\.items = items;976 res\.redirect(\'back\');977});978979app\.get(\'/add\-to\-cart\', function(req, res){980 // When redirected back to GET /add\-to\-cart981 // we could check req\.session\.items && req\.session\.items\.length982 // to print out a message983 if (req\.session\.items && req\.session\.items\.length) {984 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);985 }986 res\.render(\'shopping\-cart\');987});988.989.fi990.991.IP "" 0992.993.P994The \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\.995.

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 999–1042why, one step back
999.SS "req\.header(key[, defaultValue])"
1000Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1001.1002.IP "" 41003.1004.nf10051006req\.header(\'Host\');1007req\.header(\'host\');1008req\.header(\'Accept\', \'*/*\');1009.1010.fi1011.1012.IP "" 01013.1014.SS "req\.accepts(type)"1015Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1016.1017.P1018When 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\.1019.1020.IP "" 41021.1022.nf10231024// Accept: text/html1025req\.accepts(\'html\');1026// => true10271028// Accept: text/*; application/json1029req\.accepts(\'html\');1030req\.accepts(\'text/html\');1031req\.accepts(\'text/plain\');1032req\.accepts(\'application/json\');1033// => true10341035req\.accepts(\'image/png\');1036req\.accepts(\'png\');1037// => false1038.1039.fi1040.1041.IP "" 01042.

Added req.is() docsTj Holowaychukbefore adoption806aefa

lines 1043–1100why, one step back
1043.SS "req\.is(type)"
1044Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.1045.1046.IP "" 41047.1048.nf10491050 // With Content\-Type: text/html; charset=utf\-81051 req\.is(\'html\');1052 req\.is(\'text/html\');1053 // => true10541055 // When Content\-Type is application/json1056 req\.is(\'json\');1057 req\.is(\'application/json\');1058 // => true10591060 req\.is(\'html\');1061 // => false1062.1063.fi1064.1065.IP "" 01066.1067.P1068Ad\-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:1069.1070.IP "" 41071.1072.nf10731074 app\.is(\'an image\', function(req){1075 return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1076 });1077.1078.fi1079.1080.IP "" 01081.1082.P1083Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1084.1085.IP "" 41086.1087.nf10881089 app\.post(\'/image/upload\', function(req, res, next){1090 if (req\.is(\'an image\')) {1091 // do something1092 } else {1093 next();1094 }1095 });1096.1097.fi1098.1099.IP "" 01100.

Merge branch 'is'Tj Holowaychukbefore adoption7a71380

lines 1101–1129why, one step back
1101.P
1102Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1103.1104.P1105Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1106.1107.IP "" 41108.1109.nf11101111req\.is(\'image/*\');1112.1113.fi1114.1115.IP "" 01116.1117.P1118We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1119.1120.IP "" 41121.1122.nf11231124req\.is(\'*/json\');1125.1126.fi1127.1128.IP "" 01129.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1130–1330why, one step back
1130.SS "req\.param(name)"
1131Return the value of param \fIname\fR when present\.1132.1133.IP "\(bu" 41134Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1135.1136.IP "\(bu" 41137Checks query string params (\fIreq\.query\fR), ex: ?id=121138.1139.IP "\(bu" 41140Checks urlencoded body params (\fIreq\.body\fR), ex: id=121141.1142.IP "" 01143.1144.P1145To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.1146.1147.SS "req\.flash(type[, msg])"1148Queue flash \fImsg\fR of the given \fItype\fR\.1149.1150.IP "" 41151.1152.nf11531154req\.flash(\'info\', \'email sent\');1155req\.flash(\'error\', \'email delivery failed\');1156req\.flash(\'info\', \'email re\-sent\');1157// => 211581159req\.flash(\'info\');1160// => [\'email sent\', \'email re\-sent\']11611162req\.flash(\'info\');1163// => []11641165req\.flash();1166// => { error: [\'email delivery failed\'], info: [] }1167.1168.fi1169.1170.IP "" 01171.1172.P1173Flash notification message may also utilize formatters, by default only the %s string formatter is available:1174.1175.IP "" 41176.1177.nf11781179req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1180.1181.fi1182.1183.IP "" 01184.1185.SS "req\.isXMLHttpRequest"1186Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1187.1188.IP "" 41189.1190.nf11911192req\.xhr1193req\.isXMLHttpRequest1194.1195.fi1196.1197.IP "" 01198.1199.SS "res\.header(key[, val])"1200Get or set the response header \fIkey\fR\.1201.1202.IP "" 41203.1204.nf12051206res\.header(\'Content\-Length\');1207// => undefined12081209res\.header(\'Content\-Length\', 123);1210// => 12312111212res\.header(\'Content\-Length\');1213// => 1231214.1215.fi1216.1217.IP "" 01218.1219.SS "res\.contentType(type)"1220Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1221.1222.IP "" 41223.1224.nf12251226 var filename = \'path/to/image\.png\';1227 res\.contentType(filename);1228 // res\.headers[\'Content\-Type\'] is now "image/png"1229.1230.fi1231.1232.IP "" 01233.1234.SS "res\.attachment([filename])"1235Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1236.1237.IP "" 41238.1239.nf12401241 res\.attachment(\'path/to/my/image\.png\');1242.1243.fi1244.1245.IP "" 01246.1247.SS "res\.sendfile(path)"1248Used by \fBres\.download()\fR to transfer an arbitrary file\.1249.1250.IP "" 41251.1252.nf12531254res\.sendfile(\'path/to/my\.file\');1255.1256.fi1257.1258.IP "" 01259.1260.P1261This 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\.1262.1263.IP "" 41264.1265.nf12661267res\.sendfile(path, function(err, path){1268 if (err) {1269 // handle the error1270 } else {1271 console\.log(\'transferred %s\', path);1272 }1273});1274.1275.fi1276.1277.IP "" 01278.1279.P1280When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.1281.1282.SS "res\.download(file[, filename])"1283Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1284.1285.IP "" 41286.1287.nf12881289res\.download(\'path/to/image\.png\');1290res\.download(\'path/to/image\.png\', \'foo\.png\');1291.1292.fi1293.1294.IP "" 01295.1296.P1297This is equivalent to:1298.1299.IP "" 41300.1301.nf13021303res\.attachment(file);1304res\.sendfile(file);1305.1306.fi1307.1308.IP "" 01309.1310.SS "res\.send(body|status[, headers|status[, status]])"1311The \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:1312.1313.IP "" 41314.1315.nf13161317 res\.send(); // 2041318 res\.send(new Buffer(\'wahoo\'));1319 res\.send({ some: \'json\' });1320 res\.send(\'<p>some html</p>\');1321 res\.send(\'Sorry, cant find that\', 404);1322 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1323 res\.send(404);1324.1325.fi1326.1327.IP "" 01328.1329.P1330By 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 1331–1333why, one step back
1331.
1332.P1333Note 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 1334–1425why, one step back
1334.
1335.SS "res\.redirect(url[, status])"1336Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1337.1338.IP "" 41339.1340.nf13411342res\.redirect(\'/\', 301);1343res\.redirect(\'/account\');1344res\.redirect(\'http://google\.com\');1345res\.redirect(\'home\');1346res\.redirect(\'back\');1347.1348.fi1349.1350.IP "" 01351.1352.P1353Express 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 "/"\.1354.1355.SS "res\.cookie(name, val[, options])"1356Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1357.1358.IP "" 41359.1360.nf13611362// "Remember me" for 15 minutes1363res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1364.1365.fi1366.1367.IP "" 01368.1369.P1370To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1371.1372.IP "" 41373.1374.nf13751376app\.use(express\.cookieDecoder());13771378app\.get(\'/\', function(req, res){1379 // use req\.cookies\.rememberme1380});1381.1382.fi1383.1384.IP "" 01385.1386.SS "res\.clearCookie(name)"1387Clear cookie \fIname\fR by setting "expires" far in the past\.1388.1389.IP "" 41390.1391.nf13921393res\.clearCookie(\'rememberme\');1394.1395.fi1396.1397.IP "" 01398.1399.SS "res\.render(view[, options[, fn]])"1400Render \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\.1401.1402.P1403Most 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:1404.1405.IP "\(bu" 41406\fIscope\fR Template evaluation context (value of \fIthis\fR)1407.1408.IP "\(bu" 41409\fIlocals\fR Object containing local variables1410.1411.IP "\(bu" 41412\fIdebug\fR Output debugging information1413.1414.IP "\(bu" 41415\fIstatus\fR Response status code, defaults to 2001416.1417.IP "\(bu" 41418\fIheaders\fR Response headers object1419.1420.IP "" 01421.1422.SS "res\.partial(view[, options])"1423Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1424.1425.IP "\(bu" 4

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1427–1428why, one step back
1427.
1428.IP "\(bu" 4

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1432–1454why, one step back
1432as: \'something\' will add the \fIsomething\fR local variable
1433.1434.IP "\(bu" 41435as: this will use the collection value as the template context1436.1437.IP "\(bu" 41438as: global will merge the collection value\'s properties with \fIlocals\fR1439.1440.IP "" 014411442.1443.IP "\(bu" 41444\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\.1445.1446.IP "" 01447.1448.P1449The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1450.1451.IP "" 41452.1453.nf1454

Regenerated docsTj Holowaychukbefore adoption2a40cec

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1457–1500why, one step back
1457partial(\'movie\.jade\', { collection: movies });
1458partial(\'movie\.jade\', movies);1459partial(\'movie\', movies);1460// In view: movie\.director1461.1462.fi1463.1464.IP "" 01465.1466.P1467To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1468.1469.IP "" 41470.1471.nf14721473partial(\'movie\', { collection: movies, as: \'video\' });1474// In view: video\.director1475.1476.fi1477.1478.IP "" 01479.1480.P1481Also 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\.1482.1483.IP "" 41484.1485.nf14861487partial(\'movie\', { collection: movies, as: this });1488// In view: this\.director1489.1490.fi1491.1492.IP "" 01493.1494.P1495Another 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:1496.1497.IP "" 41498.1499.nf1500

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1502–1507why, one step back
1502// In view: director
1503.1504.fi1505.1506.IP "" 01507.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 1508–1544why, one step back
1508.P
1509This same logic applies to a single partial object usage:1510.1511.IP "" 41512.1513.nf15141515partial(\'movie\', { object: movie, as: this });1516// In view: this\.director15171518partial(\'movie\', { object: movie, as: global });1519// In view: director15201521partial(\'movie\', { object: movie, as: \'video\' });1522// In view: video\.director15231524partial(\'movie\', { object: movie });1525// In view: movie\.director1526.1527.fi1528.1529.IP "" 01530.1531.P1532When 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:1533.1534.IP "" 41535.1536.nf15371538partial(\'movie\', movie);1539// => In view: movie\.director1540.1541.fi1542.1543.IP "" 01544.

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

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

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 1554–1567why, one step back
1554// => \.\.\.path\.\.\.
1555.1556.fi1557.1558.IP "" 01559.1560.P1561Alternatively you may simply access the settings via \fIapp\.settings\fR:1562.1563.IP "" 41564.1565.nf15661567app\.settings\.views

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1568–1803why, one step back
1568// => \.\.\.path\.\.\.
1569.1570.fi1571.1572.IP "" 01573.1574.SS "app\.enable(name)"1575Enable the given setting \fIname\fR:1576.1577.IP "" 41578.1579.nf15801581app\.enable(\'some arbitrary setting\');1582app\.set(\'some arbitrary setting\');1583// => true1584.1585.fi1586.1587.IP "" 01588.1589.SS "app\.disable(name)"1590Disable the given setting \fIname\fR:1591.1592.IP "" 41593.1594.nf15951596app\.disable(\'some setting\');1597app\.set(\'some setting\');1598// => false1599.1600.fi1601.1602.IP "" 01603.1604.SS "app\.configure(env|function[, function])"1605Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1606.1607.IP "" 41608.1609.nf16101611app\.configure(function(){1612 // executed for each env1613});16141615app\.configure(\'development\', function(){1616 // executed for \'development\' only1617});1618.1619.fi1620.1621.IP "" 01622.1623.SS "app\.redirect(name, val)"1624For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1625.1626.IP "" 41627.1628.nf16291630app\.redirect(\'google\', \'http://google\.com\');1631.1632.fi1633.1634.IP "" 01635.1636.P1637Now in a route we may call:1638.1639.P1640res\.redirect(\'google\');1641.1642.P1643We may also map dynamic redirects:1644.1645.IP "" 41646.1647.nf16481649app\.redirect(\'comments\', function(req, res){1650 return \'/post/\' + req\.params\.id + \'/comments\';1651});1652.1653.fi1654.1655.IP "" 01656.1657.P1658So 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\.1659.1660.IP "" 41661.1662.nf16631664app\.get(\'/post/:id\', function(req, res){1665 res\.redirect(\'comments\');1666});1667.1668.fi1669.1670.IP "" 01671.1672.SS "app\.error(function)"1673Adds 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:1674.1675.IP "" 41676.1677.nf16781679app\.error(function(err, req, res, next){1680 res\.send(err\.message, 500);1681});1682.1683.fi1684.1685.IP "" 01686.1687.SS "app\.helpers(obj)"1688Registers static view helpers\.1689.1690.IP "" 41691.1692.nf16931694app\.helpers({1695 name: function(first, last){ return first + \', \' + last },1696 firstName: \'tj\',1697 lastName: \'holowaychuk\'1698});1699.1700.fi1701.1702.IP "" 01703.1704.P1705Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1706.1707.IP "" 41708.1709.nf17101711<%= name(firstName, lastName) %>1712.1713.fi1714.1715.IP "" 01716.1717.SS "app\.dynamicHelpers(obj)"1718Registers 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\.1719.1720.IP "" 41721.1722.nf17231724app\.dynamicHelpers({1725 session: function(req, res){1726 return req\.session;1727 }1728});1729.1730.fi1731.1732.IP "" 01733.1734.P1735All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1736.1737.IP "" 41738.1739.nf17401741<%= session\.name %>1742.1743.fi1744.1745.IP "" 01746.1747.SS "app\.mounted(fn)"1748Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1749.1750.IP "" 41751.1752.nf17531754var app = express\.createServer(),1755 blog = express\.createServer();17561757blog\.mounted(function(parent){1758 // parent is app1759 // "this" is blog1760});17611762app\.use(blog);1763.1764.fi1765.1766.IP "" 01767.1768.SS "app\.register(ext, exports)"1769Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:1770.1771.IP "" 41772.1773.nf17741775 app\.register(\'\.html\', require(\'jade\'));1776.1777.fi1778.1779.IP "" 01780.1781.P1782This 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":1783.1784.IP "" 41785.1786.nf17871788 app\.register(\'\.haml\', require(\'haml\-js\'));1789.1790.fi1791.1792.IP "" 01793.1794.P1795For engines that do not comply with the Express specification, we can also wrap their api this way\.1796.1797.IP "" 41798.1799.nf18001801 app\.register(\'\.foo\', {1802 render: function(str, options) {1803 // perhaps their api is

Regenerated docsTj Holowaychukbefore adoption5152823

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

Removed another sys requireTj Holowaychukbefore adoptionc5c3a82

lines 1805–1859why, one step back
1805 }
1806 });1807.1808.fi1809.1810.IP "" 01811.1812.SS "app\.listen([port[, host]])"1813Bind 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\.1814.1815.IP "" 41816.1817.nf18181819app\.listen();1820app\.listen(3000);1821app\.listen(3000, \'n\.n\.n\.n\');1822.1823.fi1824.1825.IP "" 01826.1827.P1828The \fIport\fR argument may also be a string representing the path to a unix domain socket:1829.1830.IP "" 41831.1832.nf18331834app\.listen(\'/tmp/express\.sock\');1835.1836.fi1837.1838.IP "" 01839.1840.P1841Then try it out:1842.1843.IP "" 41844.1845.nf18461847$ telnet /tmp/express\.sock1848GET / HTTP/1\.118491850HTTP/1\.1 200 OK1851Content\-Type: text/plain1852Content\-Length: 1118531854Hello World1855.1856.fi1857.1858.IP "" 01859