Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,316 lines · 25.6 KiB

Last changed by

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

History of this file

Take it

1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "GUIDE" "" "September 2010" "" ""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.P36git clone, first update the submodules:37.38.IP "" 439.40.nf4142$ git submodule update \-\-init43$ make install44$ make install\-support45.46.fi47.48.IP "" 049.50.SS "Creating An Application"51The \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\.52.53.IP "" 454.55.nf5657var app = require(\'express\')\.createServer();5859app\.get(\'/\', function(req, res){60    res\.send(\'hello world\');61});6263app\.listen(3000);64.65.fi66.67.IP "" 068.69.SS "Configuration"70Express 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\.71.72.P73In 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\.74.75.IP "" 476.77.nf7879app\.configure(function(){80    app\.use(express\.methodOverride());81    app\.use(express\.bodyDecoder());82    app\.use(app\.router);83    app\.use(express\.staticProvider(__dirname + \'/public\'));84});8586app\.configure(\'development\', function(){87    app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));88});8990app\.configure(\'production\', function(){91    app\.use(express\.errorHandler());92});93.94.fi95.96.IP "" 097.98.P99For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:100.101.IP "" 4102.103.nf104105app\.configure(function(){106    app\.set(\'views\', __dirname + \'/views\');107    app\.set(\'views\');108    // => "\.\.\. views directory \.\.\."109110    app\.enable(\'some feature\');111    // same as app\.set(\'some feature\', true);112113    app\.disable(\'some feature\');114    // same as app\.set(\'some feature\', false);115});116.117.fi118.119.IP "" 0120.121.P122To alter the environment we can set the \fICONNECT_ENV\fR environment variable, or more specifically \fIEXPRESS_ENV\fR, for example:123.124.IP "" 4125.126.nf127128$ EXPRESS_ENV=production node app\.js129.130.fi131.132.IP "" 0133.134.SS "Settings"135Express supports the following settings out of the box:136.137.IP "\(bu" 4138\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR139.140.IP "\(bu" 4141\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.142.143.IP "\(bu" 4144\fIviews\fR Root views directory defaulting to \fBCWD/views\fR145.146.IP "\(bu" 4147\fIview engine\fR Default view engine name for views rendered without extensions148.149.IP "\(bu" 4150\fIview options\fR An object specifying global view options151.152.IP "\(bu" 4153\fIpartials\fR Root view partials directory defaulting to \fIviews\fR/partials\.154.155.IP "" 0156.157.SS "Routing"158Express 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\.159.160.IP "" 4161.162.nf163164app\.get(\'/user/:id\', function(req, res){165    res\.send(\'user \' + req\.params\.id);166});167.168.fi169.170.IP "" 0171.172.P173A 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:174.175.IP "" 4176.177.nf178179\e/user\e/([^\e/]+)\e/?180.181.fi182.183.IP "" 0184.185.P186Regular 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\.187.188.IP "" 4189.190.nf191192app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){193    res\.send(req\.params);194});195.196.fi197.198.IP "" 0199.200.P201Curl requests against the previously defined route:202.203.IP "" 4204.205.nf206207   $ curl http://dev:3000/user208   [null,null]209   $ curl http://dev:3000/users210   [null,null]211   $ curl http://dev:3000/users/1212   ["1",null]213   $ curl http://dev:3000/users/1\.\.15214   ["1","15"]215.216.fi217.218.IP "" 0219.220.P221Below are some route examples, and the associated paths that they may consume:222.223.IP "" 4224.225.nf226227 "/user/:id"228 /user/12229230 "/users/:id?"231 /users/5232 /users233234 "/files/*"235 /files/jquery\.js236 /files/javascripts/jquery\.js237238 "/file/*\.*"239 /files/jquery\.js240 /files/javascripts/jquery\.js241242 "/user/:id/:operation?"243 /user/1244 /user/1/edit245246 "/products\.:format"247 /products\.json248 /products\.xml249250 "/products\.:format?"251 /products\.json252 /products\.xml253 /products254.255.fi256.257.IP "" 0258.259.SS "Passing Route Control"260We 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\.261.262.IP "" 4263.264.nf265266app\.get(\'/users/:id?\', function(req, res, next){267    var id = req\.params\.id;268    if (id) {269        // do something270    } else {271        next();272    }273});274275app\.get(\'/users\', function(req, res){276    // do something else277});278.279.fi280.281.IP "" 0282.283.SS "Middleware"284The Express \fIPlugin\fR is no more! middleware via Connect \fIhttp://github\.com/senchalabs/connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:285.286.IP "" 4287.288.nf289290var express = require(\'express\');291292var app = express\.createServer(293    express\.logger(),294    express\.bodyDecoder()295);296.297.fi298.299.IP "" 0300.301.P302Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:303.304.IP "" 4305.306.nf307308app\.use(express\.logger({ format: \':method :uri\' }));309.310.fi311.312.IP "" 0313.314.P315Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:316.317.IP "" 4318.319.nf320321var connect = require(\'connect\');322app\.use(connect\.logger());323.324.fi325.326.IP "" 0327.328.P329This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:330.331.IP "" 4332.333.nf334335app\.use(express\.logger());336.337.fi338.339.IP "" 0340.341.SS "Error Handling"342Express 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:343.344.IP "" 4345.346.nf347348function NotFound(msg){349    this\.name = \'NotFound\';350    Error\.call(this, msg);351    Error\.captureStackTrace(this, arguments\.callee);352}353354sys\.inherits(NotFound, Error);355356app\.get(\'/404\', function(req, res){357    throw new NotFound;358});359360app\.get(\'/500\', function(req, res){361    throw new Error(\'keyboard cat!\');362});363.364.fi365.366.IP "" 0367.368.P369We 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\.370.371.P372Note 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\.373.374.IP "" 4375.376.nf377378app\.error(function(err, req, res, next){379    if (err instanceof NotFound) {380        res\.render(\'404\.jade\');381    } else {382        next(err);383    }384});385.386.fi387.388.IP "" 0389.390.P391Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like392.393.IP "" 4394.395.nf396397app\.error(function(err, req, res){398    res\.render(\'500\.jade\', {399       locals: {400           error: err401       }402    });403});404.405.fi406.407.IP "" 0408.409.P410Our 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:411.412.IP "" 4413.414.nf415416app\.use(express\.errorHandler({ dumpExceptions: true }));417.418.fi419.420.IP "" 0421.422.P423Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:424.425.IP "" 4426.427.nf428429app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));430.431.fi432.433.IP "" 0434.435.P436The \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\.437.438.SS "View Rendering"439View 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\.440.441.P442Below 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\.443.444.IP "" 4445.446.nf447448app\.get(\'/\', function(req, res){449    res\.render(\'index\.haml\', {450        locals: { title: \'My Site\' }451    });452});453.454.fi455.456.IP "" 0457.458.P459The 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:460.461.IP "" 4462.463.nf464465app\.set(\'view engine\', \'jade\');466.467.fi468.469.IP "" 0470.471.P472Allowing us to render with:473.474.IP "" 4475.476.nf477478res\.render(\'index\');479.480.fi481.482.IP "" 0483.484.P485vs:486.487.IP "" 4488.489.nf490491res\.render(\'index\.jade\');492.493.fi494.495.IP "" 0496.497.P498When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:499.500.IP "" 4501.502.nf503504res\.render(\'another\-page\.ejs\');505.506.fi507.508.IP "" 0509.510.P511Express 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:512.513.IP "" 4514.515.nf516517app\.set(\'view options\', {518    layout: false519});520.521.fi522.523.IP "" 0524.525.P526Which can then be overridden within the \fBres\.render()\fR call if need be:527.528.IP "" 4529.530.nf531532res\.render(\'myview\.ejs\', { layout: true });533.534.fi535.536.IP "" 0537.538.P539A good example of this is specifying custom \fIejs\fR opening and closing tags:540.541.IP "" 4542.543.nf544545app\.set(\'view options\', {546    open: \'{{\',547    close: \'}}\'548});549.550.fi551.552.IP "" 0553.554.SS "View Partials"555The 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:556.557.IP "" 4558.559.nf560561partial(\'comment\.haml\', { collection: comments });562.563.fi564.565.IP "" 0566.567.P568To 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\.569.570.IP "" 4571.572.nf573574partial(\'comment\', { collection: comments });575.576.fi577.578.IP "" 0579.580.P581And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:582.583.IP "" 4584.585.nf586587partial(\'comments\', comments);588.589.fi590.591.IP "" 0592.593.P594When using the partial collection support a few "magic" variables are provided for free:595.596.IP "\(bu" 4597\fIfirstInCollection\fR True if this is the first object598.599.IP "\(bu" 4600\fIindexInCollection\fR Index of the object in the collection601.602.IP "\(bu" 4603\fIlastInCollection\fR True if this is the last object604.605.IP "" 0606.607.SS "Template Engines"608Below are a few template engines commonly used with Express:609.610.IP "\(bu" 4611Jade \fIhttp://jade\-lang\.com\fR haml\.js successor612.613.IP "\(bu" 4614Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates615.616.IP "\(bu" 4617EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript618.619.IP "" 0620.621.SS "req\.header(key[, defaultValue])"622Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:623.624.IP "" 4625.626.nf627628req\.header(\'Host\');629req\.header(\'host\');630req\.header(\'Accept\', \'*/*\');631.632.fi633.634.IP "" 0635.636.SS "req\.accepts(type)"637Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.638.639.P640When 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\.641.642.IP "" 4643.644.nf645646// Accept: text/html647req\.accepts(\'html\');648// => true649650// Accept: text/*; application/json651req\.accepts(\'html\');652req\.accepts(\'text/html\');653req\.accepts(\'text/plain\');654req\.accepts(\'application/json\');655// => true656657req\.accepts(\'image/png\');658req\.accepts(\'png\');659// => false660.661.fi662.663.IP "" 0664.665.SS "req\.param(name)"666Return the value of param \fIname\fR when present\.667.668.IP "\(bu" 4669Checks route placeholders (\fIreq\.params\fR), ex: /user/:id670.671.IP "\(bu" 4672Checks query string params (\fIreq\.query\fR), ex: ?id=12673.674.IP "\(bu" 4675Checks urlencoded body params (\fIreq\.body\fR), ex: id=12676.677.IP "" 0678.679.P680To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.681.682.SS "req\.flash(type[, msg])"683Queue flash \fImsg\fR of the given \fItype\fR\.684.685.IP "" 4686.687.nf688689req\.flash(\'info\', \'email sent\');690req\.flash(\'error\', \'email delivery failed\');691req\.flash(\'info\', \'email re\-sent\');692// => 2693694req\.flash(\'info\');695// => [\'email sent\', \'email re\-sent\']696697req\.flash(\'info\');698// => []699700req\.flash();701// => { error: [\'email delivery failed\'], info: [] }702.703.fi704.705.IP "" 0706.707.P708Flash notification message may also utilize formatters, by default only the %s string formatter is available:709.710.IP "" 4711.712.nf713714req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);715.716.fi717.718.IP "" 0719.720.SS "req\.isXMLHttpRequest"721Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:722.723.IP "" 4724.725.nf726727req\.xhr728req\.isXMLHttpRequest729.730.fi731.732.IP "" 0733.734.SS "res\.header(key[, val])"735Get or set the response header \fIkey\fR\.736.737.IP "" 4738.739.nf740741res\.header(\'Content\-Length\');742// => undefined743744res\.header(\'Content\-Length\', 123);745// => 123746747res\.header(\'Content\-Length\');748// => 123749.750.fi751.752.IP "" 0753.754.SS "res\.contentType(type)"755Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.756.757.IP "" 4758.759.nf760761  var filename = \'path/to/image\.png\';762  res\.contentType(filename);763  // res\.headers[\'Content\-Type\'] is now "image/png"764.765.fi766.767.IP "" 0768.769.SS "res\.attachment([filename])"770Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.771.772.IP "" 4773.774.nf775776  res\.attachment(\'path/to/my/image\.png\');777.778.fi779.780.IP "" 0781.782.SS "res\.sendfile(path)"783Used by \fBres\.download()\fR to transfer an arbitrary file\.784.785.IP "" 4786.787.nf788789res\.sendfile(\'path/to/my\.file\');790.791.fi792.793.IP "" 0794.795.P796This is \fInot\fR a substitution for Connect\'s \fIstaticProvider\fR middleware, it does not support HTTP caching, and does not perform any security checks\. This method is utilized by \fIres\.download()\fR to transfer static files, and allows you do to so from outside of the public directory, so suitable security checks should be applied\.797.798.SS "res\.download(file[, filename])"799Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.800.801.IP "" 4802.803.nf804805res\.download(\'path/to/image\.png\');806res\.download(\'path/to/image\.png\', \'foo\.png\');807.808.fi809.810.IP "" 0811.812.P813This is equivalent to:814.815.IP "" 4816.817.nf818819res\.attachment(file);820res\.sendfile(file);821.822.fi823.824.IP "" 0825.826.SS "res\.send(body|status[, headers|status[, status]])"827The \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:828.829.IP "" 4830.831.nf832833 res\.send(); // 204834 res\.send(new Buffer(\'wahoo\'));835 res\.send({ some: \'json\' });836 res\.send(\'<p>some html</p>\');837 res\.send(\'Sorry, cant find that\', 404);838 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);839 res\.send(404);840.841.fi842.843.IP "" 0844.845.P846By 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\.847.848.SS "res\.redirect(url[, status])"849Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.850.851.IP "" 4852.853.nf854855res\.redirect(\'/\', 301);856res\.redirect(\'/account\');857res\.redirect(\'http://google\.com\');858res\.redirect(\'home\');859res\.redirect(\'back\');860.861.fi862.863.IP "" 0864.865.P866Express 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 "/"\.867.868.SS "res\.cookie(name, val[, options])"869Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.870.871.IP "" 4872.873.nf874875// "Remember me" for 15 minutes876res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });877.878.fi879.880.IP "" 0881.882.P883To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:884.885.IP "" 4886.887.nf888889app\.use(express\.cookieDecoder());890891app\.get(\'/\', function(req, res){892    // use req\.cookies\.rememberme893});894.895.fi896.897.IP "" 0898.899.SS "res\.clearCookie(name)"900Clear cookie \fIname\fR by setting "expires" far in the past\.901.902.IP "" 4903.904.nf905906res\.clearCookie(\'rememberme\');907.908.fi909.910.IP "" 0911.912.SS "res\.render(view[, options[, fn]])"913Render \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\.914.915.P916Most 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:917.918.IP "\(bu" 4919\fIcontext|scope\fR Template evaluation context (\fIthis\fR)920.921.IP "\(bu" 4922\fIlocals\fR Object containing local variables923.924.IP "\(bu" 4925\fIdebug\fR Output debugging information926.927.IP "\(bu" 4928\fIstatus\fR Response status code, defaults to 200929.930.IP "\(bu" 4931\fIheaders\fR Response headers object932.933.IP "" 0934.935.SS "res\.partial(view[, options])"936Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.937.938.IP "\(bu" 4939\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.940.941.IP "\(bu" 4942as: \'something\' will add the \fIsomething\fR local variable943.944.IP "\(bu" 4945as: this will use the collection value as the template context946.947.IP "\(bu" 4948as: global will merge the collection value\'s properties with \fIlocals\fR949.950.IP "" 0951952.953.IP "\(bu" 4954\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\.955.956.IP "" 0957.958.P959The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.960.961.IP "" 4962.963.nf964965partial(\'movie\.jade\', { collection: movies });966partial(\'movie\.jade\', movies);967partial(\'movie\', movies);968// In view: movie\.director969.970.fi971.972.IP "" 0973.974.P975To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:976.977.IP "" 4978.979.nf980981partial(\'movie\', { collection: movies, as: \'video\' });982// In view: video\.director983.984.fi985.986.IP "" 0987.988.P989Also 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\.990.991.IP "" 4992.993.nf994995partial(\'movie\', { collection: movies, as: this });996// In view: this\.director997.998.fi999.1000.IP "" 01001.1002.P1003Another 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:1004.1005.IP "" 41006.1007.nf10081009partials(\'movie\', { collection: movies, as: global });1010// In view: director1011.1012.fi1013.1014.IP "" 01015.1016.SS "app\.set(name[, val])"1017Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1018.1019.IP "" 41020.1021.nf10221023app\.set(\'views\', __dirname + \'/views\');1024app\.set(\'views\');1025// => \.\.\.path\.\.\.1026.1027.fi1028.1029.IP "" 01030.1031.SS "app\.enable(name)"1032Enable the given setting \fIname\fR:1033.1034.IP "" 41035.1036.nf10371038app\.enable(\'some arbitrary setting\');1039app\.set(\'some arbitrary setting\');1040// => true1041.1042.fi1043.1044.IP "" 01045.1046.SS "app\.disable(name)"1047Disable the given setting \fIname\fR:1048.1049.IP "" 41050.1051.nf10521053app\.disable(\'some setting\');1054app\.set(\'some setting\');1055// => false1056.1057.fi1058.1059.IP "" 01060.1061.SS "app\.configure(env|function[, function])"1062Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1063.1064.IP "" 41065.1066.nf10671068app\.configure(function(){1069    // executed for each env1070});10711072app\.configure(\'development\', function(){1073    // executed for \'development\' only1074});1075.1076.fi1077.1078.IP "" 01079.1080.SS "app\.redirect(name, val)"1081For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1082.1083.IP "" 41084.1085.nf10861087app\.redirect(\'google\', \'http://google\.com\');1088.1089.fi1090.1091.IP "" 01092.1093.P1094Now in a route we may call:1095.1096.P1097res\.redirect(\'google\');1098.1099.P1100We may also map dynamic redirects:1101.1102.IP "" 41103.1104.nf11051106app\.redirect(\'comments\', function(req, res){1107    return \'/post/\' + req\.params\.id + \'/comments\';1108});1109.1110.fi1111.1112.IP "" 01113.1114.P1115So 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\.1116.1117.IP "" 41118.1119.nf11201121app\.get(\'/post/:id\', function(req, res){1122    res\.redirect(\'comments\');1123});1124.1125.fi1126.1127.IP "" 01128.1129.SS "app\.error(function)"1130Adds 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:1131.1132.IP "" 41133.1134.nf11351136app\.error(function(err, req, res, next){1137    res\.send(err\.message, 500);1138});1139.1140.fi1141.1142.IP "" 01143.1144.SS "app\.helpers(obj)"1145Registers static view helpers\.1146.1147.IP "" 41148.1149.nf11501151app\.helpers({1152    name: function(first, last){ return first + \', \' + last },1153    firstName: \'tj\',1154    lastName: \'holowaychuk\'1155});1156.1157.fi1158.1159.IP "" 01160.1161.P1162Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1163.1164.IP "" 41165.1166.nf11671168<%= name(firstName, lastName) %>1169.1170.fi1171.1172.IP "" 01173.1174.SS "app\.dynamicHelpers(obj)"1175Registers 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\.1176.1177.IP "" 41178.1179.nf11801181app\.dynamicHelpers({1182    session: function(req, res){1183        return req\.session;1184    }1185});1186.1187.fi1188.1189.IP "" 01190.1191.P1192All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1193.1194.IP "" 41195.1196.nf11971198<%= session\.name %>1199.1200.fi1201.1202.IP "" 01203.1204.SS "app\.mounted(fn)"1205Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1206.1207.IP "" 41208.1209.nf12101211var app = express\.createServer(),1212    blog = express\.createServer();12131214blog\.mounted(function(parent){1215    // parent is app1216    // "this" is blog1217});12181219app\.use(blog);1220.1221.fi1222.1223.IP "" 01224.1225.SS "app\.register(ext, exports)"1226Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:1227.1228.IP "" 41229.1230.nf12311232 app\.register(\'\.html\', require(\'jade\'));1233.1234.fi1235.1236.IP "" 01237.1238.P1239This 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":1240.1241.IP "" 41242.1243.nf12441245 app\.register(\'\.haml\', require(\'haml\-js\'));1246.1247.fi1248.1249.IP "" 01250.1251.P1252For engines that do not comply with the Express specification, we can also wrap their api this way\.1253.1254.IP "" 41255.1256.nf12571258 app\.register(\'\.foo\', {1259     render: function(str, options) {1260         // perhaps their api is1261         // foo\.toHTML(str, options);1262     }1263 });1264.1265.fi1266.1267.IP "" 01268.1269.SS "app\.listen([port[, host]])"1270Bind 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\.1271.1272.IP "" 41273.1274.nf12751276app\.listen();1277app\.listen(3000);1278app\.listen(3000, \'n\.n\.n\.n\');1279.1280.fi1281.1282.IP "" 01283.1284.P1285The \fIport\fR argument may also be a string representing the path to a unix domain socket:1286.1287.IP "" 41288.1289.nf12901291app\.listen(\'/tmp/express\.sock\');1292.1293.fi1294.1295.IP "" 01296.1297.P1298Then try it out:1299.1300.IP "" 41301.1302.nf13031304$ telnet /tmp/express\.sock1305GET / HTTP/1\.113061307HTTP/1\.1 200 OK1308Content\-Type: text/plain1309Content\-Length: 1113101311Hello World1312.1313.fi1314.1315.IP "" 01316