Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,126 lines · 22.3 KiB

Last changed by

Updated docsTj Holowaychukbefore adoptionb819366

History of this file

Take it

1.\" generated with Ronn/v0.6.62.\" http://github.com/rtomayko/ronn/3.4.TH "GUIDE" "" "August 2010" "" ""5.6.SS "Installation"7curl:8.9.IP "" 410.11.nf1213$ curl \-# http://expressjs\.com/install\.sh | sh14.15.fi16.17.IP "" 018.19.P20npm:21.22.IP "" 423.24.nf2526$ npm install express27.28.fi29.30.IP "" 031.32.P33git clone, first update the submodules:34.35.IP "" 436.37.nf3839$ git submodule update \-\-init40$ make install41$ make install\-support42.43.fi44.45.IP "" 046.47.SS "Creating An Application"48The \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\.49.50.IP "" 451.52.nf5354var app = require(\'express\')\.createServer();5556app\.get(\'/\', function(req, res){57    res\.send(\'hello world\');58});5960app\.listen(3000);61.62.fi63.64.IP "" 065.66.SS "Configuration"67Express 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\.68.69.P70In 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\.71.72.IP "" 473.74.nf7576app\.configure(function(){77    app\.use(connect\.methodOverride());78    app\.use(connect\.bodyDecoder());79    app\.use(app\.router);80    app\.use(connect\.staticProvider(__dirname + \'/public\'));81});8283app\.configure(\'development\', function(){84    app\.use(connect\.errorHandler({ dumpExceptions: true, showStack: true }));85});8687app\.configure(\'production\', function(){88    app\.use(connect\.errorHandler());89});90.91.fi92.93.IP "" 094.95.P96For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:97.98.IP "" 499.100.nf101102app\.configure(function(){103    app\.set(\'views\', __dirname + \'/views\');104    app\.set(\'views\');105    // => \"\.\.\. views directory \.\.\.\"106107    app\.enable(\'some feature\');108    // same as app\.set(\'some feature\', true);109110    app\.disable(\'some feature\');111    // same as app\.set(\'some feature\', false);112});113.114.fi115.116.IP "" 0117.118.P119To alter the environment we can set the \fICONNECT_ENV\fR environment variable, or more specifically \fIEXPRESS_ENV\fR, for example:120.121.IP "" 4122.123.nf124125$ EXPRESS_ENV=production node app\.js126.127.fi128.129.IP "" 0130.131.SS "Settings"132Express supports the following settings out of the box:133.134.IP "\(bu" 4135\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR136.137.IP "\(bu" 4138\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.139.140.IP "\(bu" 4141\fIviews\fR Root views directory defaulting to \fBCWD/views\fR142.143.IP "\(bu" 4144\fIview engine\fR Default view engine name for views rendered without extensions145.146.IP "" 0147.148.SS "Routing"149Express 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\.150.151.IP "" 4152.153.nf154155app\.get(\'/user/:id\', function(req, res){156    res\.send(\'user \' + req\.params\.id);157});158.159.fi160.161.IP "" 0162.163.P164A 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:165.166.IP "" 4167.168.nf169170\\/user\\/([^\\/]+)\\/?171.172.fi173.174.IP "" 0175.176.P177Regular 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\.178.179.IP "" 4180.181.nf182183app\.get(/^\\/users?(?:\\/(\\d+)(?:\\\.\\\.(\\d+))?)?/, function(req, res){184    res\.send(req\.params);185});186.187.fi188.189.IP "" 0190.191.P192Curl requests against the previously defined route:193.194.IP "" 4195.196.nf197198   $ curl http://dev:3000/user199   [null,null]200   $ curl http://dev:3000/users201   [null,null]202   $ curl http://dev:3000/users/1203   [\"1\",null]204   $ curl http://dev:3000/users/1\.\.15205   [\"1\",\"15\"]206.207.fi208.209.IP "" 0210.211.P212Below are some route examples, and the associated paths that they may consume:213.214.IP "" 4215.216.nf217218 \"/user/:id\"219 /user/12220221 \"/users/:id?\"222 /users/5223 /users224225 \"/files/*\"226 /files/jquery\.js227 /files/javascripts/jquery\.js228229 \"/file/*\.*\"230 /files/jquery\.js231 /files/javascripts/jquery\.js232233 \"/user/:id/:operation?\"234 /user/1235 /user/1/edit236237 \"/products\.:format\"238 /products\.json239 /products\.xml240241 \"/products\.:format?\"242 /products\.json243 /products\.xml244 /products245.246.fi247.248.IP "" 0249.250.SS "Passing Route Control"251We 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\.252.253.IP "" 4254.255.nf256257app\.get(\'/users/:id?\', function(req, res, next){258    var id = req\.params\.id;259    if (id) {260        // do something261    } else {262        next();263    }264});265266app\.get(\'/users\', function(req, res){267    // do something else268});269.270.fi271.272.IP "" 0273.274.SS "Middleware"275The Express \fIPlugin\fR is no more! middleware via Connect \fIhttp://github\.com/extjs/Connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:276.277.IP "" 4278.279.nf280281var connect = require(\'connect\'),282    express = require(\'express\');283284var app = express\.createServer(285    connect\.logger(),286    connect\.bodyDecoder()287);288.289.fi290.291.IP "" 0292.293.P294Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:295.296.IP "" 4297.298.nf299300app\.use(connect\.logger({ format: \':method :uri\' }));301.302.fi303.304.IP "" 0305.306.SS "Error Handling"307Express 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:308.309.IP "" 4310.311.nf312313function NotFound(msg){314    this\.name = \'NotFound\';315    Error\.call(this, msg);316    Error\.captureStackTrace(this, arguments\.callee);317}318319sys\.inherits(NotFound, Error);320321app\.get(\'/404\', function(req, res){322    throw new NotFound;323});324325app\.get(\'/500\', function(req, res){326    throw new Error(\'keyboard cat!\');327});328.329.fi330.331.IP "" 0332.333.P334We 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\.335.336.IP "" 4337.338.nf339340app\.error(function(err, req, res, next){341    if (err instanceof NotFound) {342        res\.render(\'404\.jade\');343    } else {344        next(err);345    }346});347.348.fi349.350.IP "" 0351.352.P353Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like354.355.IP "" 4356.357.nf358359app\.error(function(err, req, res){360    res\.render(\'500\.jade\', {361       locals: {362           error: err363       }364    });365});366.367.fi368.369.IP "" 0370.371.P372Our 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:373.374.IP "" 4375.376.nf377378app\.use(connect\.errorHandler({ dumpExceptions: true }));379.380.fi381.382.IP "" 0383.384.P385Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:386.387.IP "" 4388.389.nf390391app\.use(connect\.errorHandler({ showStack: true, dumpExceptions: true }));392.393.fi394.395.IP "" 0396.397.P398The \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\.399.400.SS "View Rendering"401View 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 (currently) export the method \fIexports\.render(str, options)\fR to comply with Express, however with will likely be extensible in the future\.402.403.P404Below 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\.405.406.IP "" 4407.408.nf409410app\.get(\'/\', function(req, res){411    res\.render(\'index\.haml\', {412        locals: { title: \'My Site\' }413    });414});415.416.fi417.418.IP "" 0419.420.P421The 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:422.423.IP "" 4424.425.nf426427app\.set(\'view engine\', \'jade\');428.429.fi430.431.IP "" 0432.433.P434Allowing us to render with:435.436.IP "" 4437.438.nf439440res\.render(\'index\');441.442.fi443.444.IP "" 0445.446.P447vs:448.449.IP "" 4450.451.nf452453res\.render(\'index\.jade\');454.455.fi456.457.IP "" 0458.459.P460When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:461.462.IP "" 4463.464.nf465466res\.render(\'another\-page\.ejs\');467.468.fi469.470.IP "" 0471.472.SS "View Partials"473The 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:474.475.IP "" 4476.477.nf478479partial(\'comment\.haml\', { collection: comments });480.481.fi482.483.IP "" 0484.485.P486To 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\.487.488.IP "" 4489.490.nf491492partial(\'comment\', { collection: comments });493.494.fi495.496.IP "" 0497.498.P499And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:500.501.IP "" 4502.503.nf504505partial(\'comments\', comments);506.507.fi508.509.IP "" 0510.511.P512When using the partial collection support a few \"magic\" variables are provided for free:513.514.IP "\(bu" 4515\fIfirstInCollection\fR True if this is the first object516.517.IP "\(bu" 4518\fIindexInCollection\fR Index of the object in the collection519.520.IP "\(bu" 4521_lastInCollection _ True if this is the last object522.523.IP "" 0524.525.SS "Template Engines"526Below are a few template engines commonly used with Express:527.528.IP "\(bu" 4529Jade \fIhttp://github\.com/visionmedia/jade\fR haml\.js successor530.531.IP "\(bu" 4532Haml \fIhttp://github\.com/visionmedia/haml\.js\fR indented templates533.534.IP "\(bu" 4535EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript536.537.IP "" 0538.539.SS "req\.header(key[, defaultValue])"540Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:541.542.IP "" 4543.544.nf545546req\.header(\'Host\');547req\.header(\'host\');548req\.header(\'Accept\', \'*/*\');549.550.fi551.552.IP "" 0553.554.SS "req\.accepts(type)"555Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.556.557.P558When 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\.559.560.IP "" 4561.562.nf563564// Accept: text/html565req\.accepts(\'html\');566// => true567568// Accept: text/*; application/json569req\.accepts(\'html\');570req\.accepts(\'text/html\');571req\.accepts(\'text/plain\');572req\.accepts(\'application/json\');573// => true574575req\.accepts(\'image/png\');576req\.accepts(\'png\');577// => false578.579.fi580.581.IP "" 0582.583.SS "req\.param(name)"584Return the value of param \fIname\fR when present\.585.586.IP "\(bu" 4587Checks route placeholders (\fIreq\.params\fR), ex: /user/:id588.589.IP "\(bu" 4590Checks query string params (\fIreq\.query\fR), ex: ?id=12591.592.IP "\(bu" 4593Checks urlencoded body params (\fIreq\.body\fR), ex: id=12594.595.IP "" 0596.597.P598To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIconnect\.bodyDecoder\fR middleware\.599.600.SS "req\.flash(type[, msg])"601Queue flash \fImsg\fR of the given \fItype\fR\.602.603.IP "" 4604.605.nf606607req\.flash(\'info\', \'email sent\');608req\.flash(\'error\', \'email delivery failed\');609req\.flash(\'info\', \'email re\-sent\');610// => 2611612req\.flash(\'info\');613// => [\'email sent\', \'email re\-sent\']614615req\.flash(\'info\');616// => []617618req\.flash();619// => { error: [\'email delivery failed\'], info: [] }620.621.fi622.623.IP "" 0624.625.SS "req\.isXMLHttpRequest"626Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:627.628.IP "" 4629.630.nf631632req\.xhr633req\.isXMLHttpRequest634.635.fi636.637.IP "" 0638.639.SS "res\.header(key[, val])"640Get or set the response header \fIkey\fR\.641.642.IP "" 4643.644.nf645646res\.header(\'Content\-Length\');647// => undefined648649res\.header(\'Content\-Length\', 123);650// => 123651652res\.header(\'Content\-Length\');653// => 123654.655.fi656.657.IP "" 0658.659.SS "res\.contentType(type)"660Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.661.662.IP "" 4663.664.nf665666  var filename = \'path/to/image\.png\';667  res\.contentType(filename);668  // res\.headers[\'Content\-Type\'] is now \"image/png\"669.670.fi671.672.IP "" 0673.674.SS "res\.attachment([filename])"675Sets the \fIContent\-Disposition\fR response header to \"attachment\", with optional \fIfilename\fR\.676.677.IP "" 4678.679.nf680681  res\.attachment(\'path/to/my/image\.png\');682.683.fi684.685.IP "" 0686.687.SS "res\.sendfile(path)"688Used by \fBres\.download()\fR to transfer an arbitrary file\.689.690.IP "" 4691.692.nf693694res\.sendfile(\'path/to/my\.file\');695.696.fi697.698.IP "" 0699.700.P701This 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\.702.703.SS "res\.download(file[, filename])"704Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.705.706.IP "" 4707.708.nf709710res\.download(\'path/to/image\.png\');711res\.download(\'path/to/image\.png\', \'foo\.png\');712.713.fi714.715.IP "" 0716.717.P718This is equivalent to:719.720.IP "" 4721.722.nf723724res\.attachment(file);725res\.sendfile(file);726.727.fi728.729.IP "" 0730.731.SS "res\.send(body|status[, headers|status[, status]])"732The \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:733.734.IP "" 4735.736.nf737738 res\.send(new Buffer(\'wahoo\'));739 res\.send({ some: \'json\' });740 res\.send(\'<p>some html</p>\');741 res\.send(\'Sorry, cant find that\', 404);742 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);743 res\.send(404);744.745.fi746.747.IP "" 0748.749.P750By 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\.751.752.SS "res\.redirect(url[, status])"753Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.754.755.IP "" 4756.757.nf758759res\.redirect(\'/\', 301);760res\.redirect(\'/account\');761res\.redirect(\'http://google\.com\');762res\.redirect(\'home\');763res\.redirect(\'back\');764.765.fi766.767.IP "" 0768.769.P770Express 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 \"/\"\.771.772.SS "res\.render(view[, options[, fn]])"773Render \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\.774.775.P776Most 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:777.778.IP "\(bu" 4779\fIcontext|scope\fR Template evaluation context (\fIthis\fR)780.781.IP "\(bu" 4782\fIlocals\fR Object containing local variables783.784.IP "\(bu" 4785\fIdebug\fR Output debugging information786.787.IP "" 0788.789.SS "res\.partial(view[, options])"790Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.791.792.IP "\(bu" 4793\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.794.795.IP "\(bu" 4796as: \'something\' will add the \fIsomething\fR local variable797.798.IP "\(bu" 4799as: this will use the collection value as the template context800.801.IP "\(bu" 4802as: global will merge the collection value\'s properties with \fIlocals\fR803.804.IP "" 0805806.807.IP "\(bu" 4808\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\.809.810.IP "" 0811.812.P813The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.814.815.IP "" 4816.817.nf818819partial(\'movie\.jade\', { collection: movies });820partial(\'movie\.jade\', movies);821partial(\'movie\', movies);822// In view: movie\.director823.824.fi825.826.IP "" 0827.828.P829To change the local from \fImovie\fR to \fIvideo\fR we can use the \"as\" option:830.831.IP "" 4832.833.nf834835partial(\'movie\', { collection: movies, as: \'video\' });836// In view: video\.director837.838.fi839.840.IP "" 0841.842.P843Also 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\.844.845.IP "" 4846.847.nf848849partial(\'movie\', { collection: movies, as: this });850// In view: this\.director851.852.fi853.854.IP "" 0855.856.P857Another 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:858.859.IP "" 4860.861.nf862863partials(\'movie\', { collection: movies, as: global });864// In view: director865.866.fi867.868.IP "" 0869.870.SS "app\.set(name[, val])"871Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:872.873.IP "" 4874.875.nf876877app\.set(\'views\', __dirname + \'/views\');878app\.set(\'views\');879// => \.\.\.path\.\.\.880.881.fi882.883.IP "" 0884.885.SS "app\.enable(name)"886Enable the given setting \fIname\fR:887.888.IP "" 4889.890.nf891892app\.enable(\'some arbitrary setting\');893app\.set(\'some arbitrary setting\');894// => true895.896.fi897.898.IP "" 0899.900.SS "app\.disable(name)"901Disable the given setting \fIname\fR:902.903.IP "" 4904.905.nf906907app\.disable(\'some setting\');908app\.set(\'some setting\');909// => false910.911.fi912.913.IP "" 0914.915.SS "app\.configure(env|function[, function])"916Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:917.918.IP "" 4919.920.nf921922app\.configure(function(){923    // executed for each env924});925926app\.configure(\'development\', function(){927    // executed for \'development\' only928});929.930.fi931.932.IP "" 0933.934.SS "app\.redirect(name, val)"935For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:936.937.IP "" 4938.939.nf940941app\.redirect(\'google\', \'http://google\.com\');942.943.fi944.945.IP "" 0946.947.P948Now in a route we may call:949.950.P951res\.redirect(\'google\');952.953.P954We may also map dynamic redirects:955.956.IP "" 4957.958.nf959960app\.redirect(\'comments\', function(req, res){961    return \'/post/\' + req\.params\.id + \'/comments\';962});963.964.fi965.966.IP "" 0967.968.P969So 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\.970.971.IP "" 4972.973.nf974975app\.get(\'/post/:id\', function(req, res){976    res\.redirect(\'comments\');977});978.979.fi980.981.IP "" 0982.983.SS "app\.error(function)"984Adds 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:985.986.IP "" 4987.988.nf989990app\.error(function(err, req, res, next){991    res\.send(err\.message, 500);992});993.994.fi995.996.IP "" 0997.998.SS "app\.helpers(obj)"999Registers static view helpers\.1000.1001.IP "" 41002.1003.nf10041005app\.helpers({1006    name: function(first, last){ return first + \', \' + last },1007    firstName: \'tj\',1008    lastName: \'holowaychuk\'1009});1010.1011.fi1012.1013.IP "" 01014.1015.P1016Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1017.1018.IP "" 41019.1020.nf10211022<%= name(firstName, lastName) %>1023.1024.fi1025.1026.IP "" 01027.1028.SS "app\.dynamicHelpers(obj)"1029Registers 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\.1030.1031.IP "" 41032.1033.nf10341035app\.dynamicHelpers({1036    session: function(req, res){1037        return req\.session;1038    }1039});1040.1041.fi1042.1043.IP "" 01044.1045.P1046All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1047.1048.IP "" 41049.1050.nf10511052<%= session\.name %>1053.1054.fi1055.1056.IP "" 01057.1058.SS "app\.mounted(fn)"1059Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1060.1061.IP "" 41062.1063.nf10641065var app = express\.createServer(),1066    blog = express\.createServer();10671068blog\.mounted(function(parent){1069    // parent is app1070    // \"this\" is blog1071});10721073app\.use(blog);1074.1075.fi1076.1077.IP "" 01078.1079.SS "app\.listen([port[, host]])"1080Bind 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\.1081.1082.IP "" 41083.1084.nf10851086app\.listen();1087app\.listen(3000);1088app\.listen(3000, \'n\.n\.n\.n\');1089.1090.fi1091.1092.IP "" 01093.1094.P1095The \fIport\fR argument may also be a string representing the path to a unix domain socket:1096.1097.IP "" 41098.1099.nf11001101app\.listen(\'/tmp/express\.sock\');1102.1103.fi1104.1105.IP "" 01106.1107.P1108Then try it out:1109.1110.IP "" 41111.1112.nf11131114$ telnet /tmp/express\.sock1115GET / HTTP/1\.111161117HTTP/1\.1 200 OK1118Content\-Type: text/plain1119Content\-Length: 1111201121Hello World1122.1123.fi1124.1125.IP "" 01126