Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,971 lines · 42.2 KiB

Last changed by

docsTj Holowaychukbefore adoption50006f7

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" "" "March 2011" "" ""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});6970app\.configure(\'development\', function(){71    app\.use(express\.staticProvider(__dirname + \'/public\'));72    app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));73});7475app\.configure(\'production\', function(){76  var oneYear = 31557600000;77    app\.use(express\.staticProvider({ root: __dirname + \'/public\', maxAge: oneYear }));78    app\.use(express\.errorHandler());79});80.81.fi82.83.IP "" 084.85.P86For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:87.88.IP "" 489.90.nf9192app\.configure(function(){93    app\.set(\'views\', __dirname + \'/views\');94    app\.set(\'views\');95    // => "\.\.\. views directory \.\.\."9697    app\.enable(\'some feature\');98    // same as app\.set(\'some feature\', true);99100    app\.disable(\'some feature\');101    // same as app\.set(\'some feature\', false);102});103.104.fi105.106.IP "" 0107.108.P109To alter the environment we can set the \fINODE_ENV\fR environment variable, for example:110.111.IP "" 4112.113.nf114115$ NODE_ENV=production node app\.js116.117.fi118.119.IP "" 0120.121.P122This is \fIvery\fR important, as many caching mechanisms are \fIonly enabled\fR when in production\.123.124.SS "Settings"125Express supports the following settings out of the box:126.127.IP "\(bu" 4128\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR129.130.IP "\(bu" 4131\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.132.133.IP "\(bu" 4134\fIviews\fR Root views directory defaulting to \fBCWD/views\fR135.136.IP "\(bu" 4137\fIview engine\fR Default view engine name for views rendered without extensions138.139.IP "\(bu" 4140\fIview options\fR An object specifying global view options141.142.IP "" 0143.144.SS "Routing"145Express 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\.146.147.IP "" 4148.149.nf150151app\.get(\'/user/:id\', function(req, res){152    res\.send(\'user \' + req\.params\.id);153});154.155.fi156.157.IP "" 0158.159.P160A 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:161.162.IP "" 4163.164.nf165166\e/user\e/([^\e/]+)\e/?167.168.fi169.170.IP "" 0171.172.P173Regular expression literals may also be passed for complex uses\. Since capture groups with literal \fIRegExp\fR\'s are anonymous we can access them directly \fBreq\.params\fR\. So our first capture group would be \fIreq\.params[0]\fR and the second would follow as \fIreq\.params[1]\fR\.174.175.IP "" 4176.177.nf178179app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){180    res\.send(req\.params);181});182.183.fi184.185.IP "" 0186.187.P188Curl requests against the previously defined route:189.190.IP "" 4191.192.nf193194   $ curl http://dev:3000/user195   [null,null]196   $ curl http://dev:3000/users197   [null,null]198   $ curl http://dev:3000/users/1199   ["1",null]200   $ curl http://dev:3000/users/1\.\.15201   ["1","15"]202.203.fi204.205.IP "" 0206.207.P208Below are some route examples, and the associated paths that they may consume:209.210.IP "" 4211.212.nf213214 "/user/:id"215 /user/12216217 "/users/:id?"218 /users/5219 /users220221 "/files/*"222 /files/jquery\.js223 /files/javascripts/jquery\.js224225 "/file/*\.*"226 /files/jquery\.js227 /files/javascripts/jquery\.js228229 "/user/:id/:operation?"230 /user/1231 /user/1/edit232233 "/products\.:format"234 /products\.json235 /products\.xml236237 "/products\.:format?"238 /products\.json239 /products\.xml240 /products241242 "/user/:id\.:format?"243 /user/12244 /user/12\.json245.246.fi247.248.IP "" 0249.250.P251For 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:252.253.IP "" 4254.255.nf256257var express = require(\'express\')258  , app = express\.createServer();259260app\.use(express\.bodyDecoder());261262app\.post(\'/\', function(req, res){263  res\.send(req\.body);264});265266app\.listen(3000);267.268.fi269.270.IP "" 0271.272.P273Express 2\.0\.0\-pre also supports named capture groups\. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, however say for example we are limiting a user id to digits, we may use \fI\'/user/:id(\ed+)\'\fR which will \fInot\fR match unless the placeholder value contains only digits\.274.275.SS "Passing Route Control"276We 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\.277.278.IP "" 4279.280.nf281282app\.get(\'/users/:id?\', function(req, res, next){283    var id = req\.params\.id;284    if (id) {285        // do something286    } else {287        next();288    }289});290291app\.get(\'/users\', function(req, res){292    // do something else293});294.295.fi296.297.IP "" 0298.299.P300Express 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:301.302.IP "" 4303.304.nf305306var express = require(\'express\')307  , app = express\.createServer();308309var users = [{ name: \'tj\' }];310311app\.all(\'/user/:id/:op?\', function(req, res, next){312  req\.user = users[req\.params\.id];313  if (req\.user) {314    next();315  } else {316    next(new Error(\'cannot find user \' + req\.params\.id));317  }318});319320app\.get(\'/user/:id\', function(req, res){321  res\.send(\'viewing \' + req\.user\.name);322});323324app\.get(\'/user/:id/edit\', function(req, res){325  res\.send(\'editing \' + req\.user\.name);326});327328app\.put(\'/user/:id\', function(req, res){329  res\.send(\'updating \' + req\.user\.name);330});331332app\.get(\'*\', function(req, res){333  res\.send(\'what???\', 404);334});335336app\.listen(3000);337.338.fi339.340.IP "" 0341.342.SS "Middleware"343Middleware 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:344.345.IP "" 4346.347.nf348349  var express = require(\'express\');350351var app = express\.createServer(352    express\.logger(),353    express\.bodyDecoder()354  );355.356.fi357.358.IP "" 0359.360.P361Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:362.363.IP "" 4364.365.nf366367app\.use(express\.logger({ format: \':method :uri\' }));368.369.fi370.371.IP "" 0372.373.P374Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:375.376.IP "" 4377.378.nf379380var connect = require(\'connect\');381app\.use(connect\.logger());382.383.fi384.385.IP "" 0386.387.P388This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:389.390.IP "" 4391.392.nf393394app\.use(express\.logger());395.396.fi397.398.IP "" 0399.400.SS "Route Middleware"401Routes 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\.402.403.P404Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.405.406.IP "" 4407.408.nf409410app\.get(\'/user/:id\', function(req, res, next){411    loadUser(req\.params\.id, function(err, user){412        if (err) return next(err);413        res\.send(\'Viewing user \' + user\.name);414    });415});416.417.fi418.419.IP "" 0420.421.P422To 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\.423.424.IP "" 4425.426.nf427428function loadUser(req, res, next) {429    // You would fetch your user from the db430    var user = users[req\.params\.id];431    if (user) {432        req\.user = user;433        next();434    } else {435        next(new Error(\'Failed to load user \' + req\.params\.id));436    }437}438439app\.get(\'/user/:id\', loadUser, function(req, res){440    res\.send(\'Viewing user \' + req\.user\.name);441});442.443.fi444.445.IP "" 0446.447.P448Multiple 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\.449.450.IP "" 4451.452.nf453454function andRestrictToSelf(req, res, next) {455    req\.authenticatedUser\.id == req\.user\.id456        ? next()457        : next(new Error(\'Unauthorized\'));458}459460app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){461    res\.send(\'Editing user \' + req\.user\.name);462});463.464.fi465.466.IP "" 0467.468.P469Keeping 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\.470.471.IP "" 4472.473.nf474475function andRestrictTo(role) {476    return function(req, res, next) {477      req\.authenticatedUser\.role == role478          ? next()479          : next(new Error(\'Unauthorized\'));480    }481}482483app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){484    res\.send(\'Deleted user \' + req\.user\.name);485});486.487.fi488.489.IP "" 0490.491.P492Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.493.494.IP "" 4495.496.nf497498var a = [middleware1, middleware2]499  , b = [middleware3, middleware4]500  , all = [a, b];501502app\.get(\'/foo\', a, function(){});503app\.get(\'/bar\', a, function(){});504505app\.get(\'/\', a, middleware3, middleware4, function(){});506app\.get(\'/\', a, b, function(){});507app\.get(\'/\', all, function(){});508.509.fi510.511.IP "" 0512.513.P514For 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\.515.516.SS "HTTP Methods"517We 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\.518.519.P520A 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\.521.522.IP "" 4523.524.nf525526 <form method="post" action="/">527     <input type="text" name="user[name]" />528     <input type="text" name="user[email]" />529     <input type="submit" value="Submit" />530 </form>531.532.fi533.534.IP "" 0535.536.P537By 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:538.539.IP "" 4540.541.nf542543app\.use(express\.bodyDecoder());544.545.fi546.547.IP "" 0548.549.P550Our 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\.551.552.IP "" 4553.554.nf555556app\.post(\'/\', function(req, res){557    console\.log(req\.body\.user);558    res\.redirect(\'back\');559});560.561.fi562.563.IP "" 0564.565.P566When 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\.567.568.IP "" 4569.570.nf571572app\.use(express\.bodyDecoder());573app\.use(express\.methodOverride());574.575.fi576.577.IP "" 0578.579.P580The 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:581.582.IP "" 4583.584.nf585586<form method="post" action="/">587  <input type="hidden" name="_method" value="put" />588  <input type="text" name="user[name]" />589  <input type="text" name="user[email]" />590  <input type="submit" value="Submit" />591</form>592593app\.put(\'/\', function(){594    console\.log(req\.body\.user);595    res\.redirect(\'back\');596});597.598.fi599.600.IP "" 0601.602.SS "Error Handling"603Express 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:604.605.IP "" 4606.607.nf608609function NotFound(msg){610    this\.name = \'NotFound\';611    Error\.call(this, msg);612    Error\.captureStackTrace(this, arguments\.callee);613}614615sys\.inherits(NotFound, Error);616617app\.get(\'/404\', function(req, res){618    throw new NotFound;619});620621app\.get(\'/500\', function(req, res){622    throw new Error(\'keyboard cat!\');623});624.625.fi626.627.IP "" 0628.629.P630We 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\.631.632.P633Note 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\.634.635.IP "" 4636.637.nf638639app\.error(function(err, req, res, next){640    if (err instanceof NotFound) {641        res\.render(\'404\.jade\');642    } else {643        next(err);644    }645});646.647.fi648.649.IP "" 0650.651.P652Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like653.654.IP "" 4655.656.nf657658app\.error(function(err, req, res){659    res\.render(\'500\.jade\', {660       locals: {661           error: err662       }663    });664});665.666.fi667.668.IP "" 0669.670.P671Our 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:672.673.IP "" 4674.675.nf676677app\.use(express\.errorHandler({ dumpExceptions: true }));678.679.fi680.681.IP "" 0682.683.P684Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:685.686.IP "" 4687.688.nf689690app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));691.692.fi693.694.IP "" 0695.696.P697The \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\.698.699.SS "Route Preconditions"700Route placeholder pre\-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls\. For example if you are constantly fetching common data for several routes, such as loading a user for \fI/user/:id\fR,we might typically do something like below:701.702.IP "" 4703.704.nf705706app\.get(\'/user/:userId\', function(req, res, next){707  User\.get(req\.params\.userId, function(err, user){708    if (err) return next(err);709    res\.send(\'user \' + user\.name);710  });711});712.713.fi714.715.IP "" 0716.717.P718With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database\. Below we invoke \fIapp\.param()\fR with the parameter name we wish to map to some middleware, as you can see we receive the \fIid\fR argument which contains the placeholder value\. Using this we load the user and perform error handling as usual, and simple call \fInext()\fR to pass control to the next precondition or route handler\.719.720.IP "" 4721.722.nf723724app\.param(\'userId\', function(req, res, next, id){725  User\.get(id, function(err, user){726    if (err) return next(err);727    if (!user) return next(new Error(\'failed to find user\'));728    req\.user = user;729    next();730  });731});732.733.fi734.735.IP "" 0736.737.P738Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:739.740.IP "" 4741.742.nf743744app\.get(\'/user/:userId\', function(req, res){745  res\.send(\'user \' + req\.user\.name);746});747.748.fi749.750.IP "" 0751.752.P753For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument)\. Any errors thrown will be passed to \fInext(err)\fR\.754.755.IP "" 4756.757.nf758759app\.param(\'number\', function(n){ return parseInt(n, 10); });760.761.fi762.763.IP "" 0764.765.P766We may also apply the same callback to several placeholders, for example a route GET \fI/commits/:from\-:to\fR are both numbers, so we may define them as an array:767.768.IP "" 4769.770.nf771772app\.param([\'from\', \'to\'], function(n){ return parseInt(n, 10); });773.774.fi775.776.IP "" 0777.778.SS "View Rendering"779View 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\.780.781.P782Below 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\.783.784.IP "" 4785.786.nf787788app\.get(\'/\', function(req, res){789    res\.render(\'index\.haml\', {790        locals: { title: \'My Site\' }791    });792});793.794.fi795.796.IP "" 0797.798.P799The 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:800.801.IP "" 4802.803.nf804805app\.set(\'view engine\', \'jade\');806.807.fi808.809.IP "" 0810.811.P812Allowing us to render with:813.814.IP "" 4815.816.nf817818res\.render(\'index\');819.820.fi821.822.IP "" 0823.824.P825vs:826.827.IP "" 4828.829.nf830831res\.render(\'index\.jade\');832.833.fi834.835.IP "" 0836.837.P838When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:839.840.IP "" 4841.842.nf843844res\.render(\'another\-page\.ejs\');845.846.fi847.848.IP "" 0849.850.P851Express 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:852.853.IP "" 4854.855.nf856857app\.set(\'view options\', {858    layout: false859});860.861.fi862.863.IP "" 0864.865.P866Which can then be overridden within the \fBres\.render()\fR call if need be:867.868.IP "" 4869.870.nf871872res\.render(\'myview\.ejs\', { layout: true });873.874.fi875.876.IP "" 0877.878.P879When 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:880.881.IP "" 4882.883.nf884885res\.render(\'page\', { layout: \'mylayout\' });886.887.fi888.889.IP "" 0890.891.P892Otherwise we must specify the extension:893.894.IP "" 4895.896.nf897898res\.render(\'page\', { layout: \'mylayout\.jade\' });899.900.fi901.902.IP "" 0903.904.P905These paths may also be absolute:906.907.IP "" 4908.909.nf910911res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });912.913.fi914.915.IP "" 0916.917.P918A good example of this is specifying custom \fIejs\fR opening and closing tags:919.920.IP "" 4921.922.nf923924app\.set(\'view options\', {925    open: \'{{\',926    close: \'}}\'927});928.929.fi930.931.IP "" 0932.933.SS "View Partials"934The 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:935.936.IP "" 4937.938.nf939940partial(\'comment\.haml\', { collection: comments });941.942.fi943.944.IP "" 0945.946.P947To 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\.948.949.IP "" 4950.951.nf952953partial(\'comment\', { collection: comments });954.955.fi956.957.IP "" 0958.959.P960And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:961.962.IP "" 4963.964.nf965966partial(\'comment\', comments);967.968.fi969.970.IP "" 0971.972.P973When using the partial collection support a few "magic" variables are provided for free:974.975.IP "\(bu" 4976\fIfirstInCollection\fR True if this is the first object977.978.IP "\(bu" 4979\fIindexInCollection\fR Index of the object in the collection980.981.IP "\(bu" 4982\fIlastInCollection\fR True if this is the last object983.984.IP "\(bu" 4985\fIcollectionLength\fR Length of the collection986.987.IP "" 0988.989.P990For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.991.992.P993NOTE: 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\.994.995.SS "Template Engines"996Below are a few template engines commonly used with Express:997.998.IP "\(bu" 4999Jade \fIhttp://jade\-lang\.com\fR haml\.js successor1000.1001.IP "\(bu" 41002Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates1003.1004.IP "\(bu" 41005EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript1006.1007.IP "\(bu" 41008CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating1009.1010.IP "\(bu" 41011jQuery Templates \fIhttps://github\.com/kof/node\-jqtpl\fR for node1012.1013.IP "" 01014.1015.SS "Session Support"1016Sessions 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\.1017.1018.IP "" 41019.1020.nf10211022app\.use(express\.cookieDecoder());1023app\.use(express\.session());1024.1025.fi1026.1027.IP "" 01028.1029.P1030By 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:1031.1032.IP "" 41033.1034.nf10351036var RedisStore = require(\'connect\-redis\');1037app\.use(express\.cookieDecoder());1038app\.use(express\.session({ store: new RedisStore }));1039.1040.fi1041.1042.IP "" 01043.1044.P1045Now 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:1046.1047.IP "" 41048.1049.nf10501051var RedisStore = require(\'connect\-redis\');1052app\.use(express\.bodyDecoder());1053app\.use(express\.cookieDecoder());1054app\.use(express\.session({ store: new RedisStore }));10551056app\.post(\'/add\-to\-cart\', function(req, res){1057  // Perhaps we posted several items with a form1058  // (use the bodyDecoder() middleware for this)1059  var items = req\.body\.items;1060  req\.session\.items = items;1061  res\.redirect(\'back\');1062});10631064app\.get(\'/add\-to\-cart\', function(req, res){1065  // When redirected back to GET /add\-to\-cart1066  // we could check req\.session\.items && req\.session\.items\.length1067  // to print out a message1068  if (req\.session\.items && req\.session\.items\.length) {1069    req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);1070  }1071  res\.render(\'shopping\-cart\');1072});1073.1074.fi1075.1076.IP "" 01077.1078.P1079The \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\.1080.1081.SS "Migration Guide"1082Pre\-beta Express developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.1083.1084.SS "req\.header(key[, defaultValue])"1085Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1086.1087.IP "" 41088.1089.nf10901091req\.header(\'Host\');1092req\.header(\'host\');1093req\.header(\'Accept\', \'*/*\');1094.1095.fi1096.1097.IP "" 01098.1099.SS "req\.accepts(type)"1100Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1101.1102.P1103When 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\.1104.1105.IP "" 41106.1107.nf11081109// Accept: text/html1110req\.accepts(\'html\');1111// => true11121113// Accept: text/*; application/json1114req\.accepts(\'html\');1115req\.accepts(\'text/html\');1116req\.accepts(\'text/plain\');1117req\.accepts(\'application/json\');1118// => true11191120req\.accepts(\'image/png\');1121req\.accepts(\'png\');1122// => false1123.1124.fi1125.1126.IP "" 01127.1128.SS "req\.is(type)"1129Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.1130.1131.IP "" 41132.1133.nf11341135   // With Content\-Type: text/html; charset=utf\-81136   req\.is(\'html\');1137   req\.is(\'text/html\');1138   // => true11391140   // When Content\-Type is application/json1141   req\.is(\'json\');1142   req\.is(\'application/json\');1143   // => true11441145   req\.is(\'html\');1146   // => false1147.1148.fi1149.1150.IP "" 01151.1152.P1153Ad\-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:1154.1155.IP "" 41156.1157.nf11581159    app\.is(\'an image\', function(req){1160      return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1161    });1162.1163.fi1164.1165.IP "" 01166.1167.P1168Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1169.1170.IP "" 41171.1172.nf11731174   app\.post(\'/image/upload\', function(req, res, next){1175     if (req\.is(\'an image\')) {1176       // do something1177     } else {1178       next();1179     }1180   });1181.1182.fi1183.1184.IP "" 01185.1186.P1187Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1188.1189.P1190Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1191.1192.IP "" 41193.1194.nf11951196req\.is(\'image/*\');1197.1198.fi1199.1200.IP "" 01201.1202.P1203We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1204.1205.IP "" 41206.1207.nf12081209req\.is(\'*/json\');1210.1211.fi1212.1213.IP "" 01214.1215.SS "req\.param(name[, default])"1216Return the value of param \fIname\fR when present or \fIdefault\fR\.1217.1218.IP "\(bu" 41219Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1220.1221.IP "\(bu" 41222Checks query string params (\fIreq\.query\fR), ex: ?id=121223.1224.IP "\(bu" 41225Checks urlencoded body params (\fIreq\.body\fR), ex: id=121226.1227.IP "" 01228.1229.P1230To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.1231.1232.SS "req\.flash(type[, msg])"1233Queue flash \fImsg\fR of the given \fItype\fR\.1234.1235.IP "" 41236.1237.nf12381239req\.flash(\'info\', \'email sent\');1240req\.flash(\'error\', \'email delivery failed\');1241req\.flash(\'info\', \'email re\-sent\');1242// => 212431244req\.flash(\'info\');1245// => [\'email sent\', \'email re\-sent\']12461247req\.flash(\'info\');1248// => []12491250req\.flash();1251// => { error: [\'email delivery failed\'], info: [] }1252.1253.fi1254.1255.IP "" 01256.1257.P1258Flash notification message may also utilize formatters, by default only the %s string formatter is available:1259.1260.IP "" 41261.1262.nf12631264req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1265.1266.fi1267.1268.IP "" 01269.1270.SS "req\.isXMLHttpRequest"1271Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1272.1273.IP "" 41274.1275.nf12761277req\.xhr1278req\.isXMLHttpRequest1279.1280.fi1281.1282.IP "" 01283.1284.SS "res\.header(key[, val])"1285Get or set the response header \fIkey\fR\.1286.1287.IP "" 41288.1289.nf12901291res\.header(\'Content\-Length\');1292// => undefined12931294res\.header(\'Content\-Length\', 123);1295// => 12312961297res\.header(\'Content\-Length\');1298// => 1231299.1300.fi1301.1302.IP "" 01303.1304.SS "res\.contentType(type)"1305Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1306.1307.IP "" 41308.1309.nf13101311  var filename = \'path/to/image\.png\';1312  res\.contentType(filename);1313  // res\.headers[\'Content\-Type\'] is now "image/png"1314.1315.fi1316.1317.IP "" 01318.1319.SS "res\.attachment([filename])"1320Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1321.1322.IP "" 41323.1324.nf13251326  res\.attachment(\'path/to/my/image\.png\');1327.1328.fi1329.1330.IP "" 01331.1332.SS "res\.sendfile(path)"1333Used by \fBres\.download()\fR to transfer an arbitrary file\.1334.1335.IP "" 41336.1337.nf13381339res\.sendfile(\'path/to/my\.file\');1340.1341.fi1342.1343.IP "" 01344.1345.P1346This 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\.1347.1348.IP "" 41349.1350.nf13511352res\.sendfile(path, function(err, path){1353  if (err) {1354    // handle the error1355  } else {1356    console\.log(\'transferred %s\', path);1357  }1358});1359.1360.fi1361.1362.IP "" 01363.1364.SS "res\.download(file[, filename])"1365Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1366.1367.IP "" 41368.1369.nf13701371res\.download(\'path/to/image\.png\');1372res\.download(\'path/to/image\.png\', \'foo\.png\');1373.1374.fi1375.1376.IP "" 01377.1378.P1379This is equivalent to:1380.1381.IP "" 41382.1383.nf13841385res\.attachment(file);1386res\.sendfile(file);1387.1388.fi1389.1390.IP "" 01391.1392.SS "res\.send(body|status[, headers|status[, status]])"1393The \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:1394.1395.IP "" 41396.1397.nf13981399 res\.send(); // 2041400 res\.send(new Buffer(\'wahoo\'));1401 res\.send({ some: \'json\' });1402 res\.send(\'<p>some html</p>\');1403 res\.send(\'Sorry, cant find that\', 404);1404 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1405 res\.send(404);1406.1407.fi1408.1409.IP "" 01410.1411.P1412By 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\.1413.1414.P1415Note 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\.1416.1417.SS "res\.redirect(url[, status])"1418Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1419.1420.IP "" 41421.1422.nf14231424res\.redirect(\'/\', 301);1425res\.redirect(\'/account\');1426res\.redirect(\'http://google\.com\');1427res\.redirect(\'home\');1428res\.redirect(\'back\');1429.1430.fi1431.1432.IP "" 01433.1434.P1435Express 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 "/"\.1436.1437.SS "res\.cookie(name, val[, options])"1438Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1439.1440.IP "" 41441.1442.nf14431444// "Remember me" for 15 minutes1445res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1446.1447.fi1448.1449.IP "" 01450.1451.P1452To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1453.1454.IP "" 41455.1456.nf14571458app\.use(express\.cookieDecoder());14591460app\.get(\'/\', function(req, res){1461    // use req\.cookies\.rememberme1462});1463.1464.fi1465.1466.IP "" 01467.1468.SS "res\.clearCookie(name)"1469Clear cookie \fIname\fR by setting "expires" far in the past\.1470.1471.IP "" 41472.1473.nf14741475res\.clearCookie(\'rememberme\');1476.1477.fi1478.1479.IP "" 01480.1481.SS "res\.render(view[, options[, fn]])"1482Render \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\.1483.1484.P1485Most 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:1486.1487.IP "\(bu" 41488\fIscope\fR Template evaluation context (value of \fIthis\fR)1489.1490.IP "\(bu" 41491\fIlocals\fR Object containing local variables1492.1493.IP "\(bu" 41494\fIdebug\fR Output debugging information1495.1496.IP "\(bu" 41497\fIstatus\fR Response status code, defaults to 2001498.1499.IP "\(bu" 41500\fIheaders\fR Response headers object1501.1502.IP "" 01503.1504.SS "res\.partial(view[, options])"1505Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1506.1507.IP "\(bu" 41508\fIobject\fR the object named by \fIas\fR or derived from the view name1509.1510.IP "\(bu" 41511\fIas\fR Variable name for each \fIcollection\fR or \fIobject\fR value, defaults to the view name\.1512.1513.IP "\(bu" 41514as: \'something\' will add the \fIsomething\fR local variable1515.1516.IP "\(bu" 41517as: this will use the collection value as the template context1518.1519.IP "\(bu" 41520as: global will merge the collection value\'s properties with \fIlocals\fR1521.1522.IP "" 015231524.1525.IP "\(bu" 41526\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\.1527.1528.IP "" 01529.1530.P1531The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1532.1533.IP "" 41534.1535.nf15361537partial(\'theatre/movie\.jade\', { collection: movies });1538partial(\'theatre/movie\.jade\', movies);1539partial(\'movie\.jade\', { collection: movies });1540partial(\'movie\.jade\', movies);1541partial(\'movie\', movies);1542// In view: movie\.director1543.1544.fi1545.1546.IP "" 01547.1548.P1549To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1550.1551.IP "" 41552.1553.nf15541555partial(\'movie\', { collection: movies, as: \'video\' });1556// In view: video\.director1557.1558.fi1559.1560.IP "" 01561.1562.P1563Also 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\.1564.1565.IP "" 41566.1567.nf15681569partial(\'movie\', { collection: movies, as: this });1570// In view: this\.director1571.1572.fi1573.1574.IP "" 01575.1576.P1577Another 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:1578.1579.IP "" 41580.1581.nf15821583partial(\'movie\', { collection: movies, as: global });1584// In view: director1585.1586.fi1587.1588.IP "" 01589.1590.P1591This same logic applies to a single partial object usage:1592.1593.IP "" 41594.1595.nf15961597partial(\'movie\', { object: movie, as: this });1598// In view: this\.director15991600partial(\'movie\', { object: movie, as: global });1601// In view: director16021603partial(\'movie\', { object: movie, as: \'video\' });1604// In view: video\.director16051606partial(\'movie\', { object: movie });1607// In view: movie\.director1608.1609.fi1610.1611.IP "" 01612.1613.P1614When 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:1615.1616.IP "" 41617.1618.nf16191620partial(\'movie\', movie);1621// => In view: movie\.director1622.1623.fi1624.1625.IP "" 01626.1627.SS "res\.local(name[, val])"1628Get or set the given local variable \fIname\fR\. The locals built up for a response are applied to those given to the view rendering methods such as \fBres\.render()\fR\.1629.1630.IP "" 41631.1632.nf16331634  app\.all(\'/movie/:id\', function(req, res, next){1635    Movie\.get(req\.params\.id, function(err, movie){1636      // Assigns res\.locals\.movie = movie1637      res\.local(\'movie\', movie);1638    });1639  });16401641  app\.get(\'/movie/:id\', function(req, res){1642    // movie is already a local, however we1643    // can pass more if we wish1644    res\.render(\'movie\', { displayReviews: true });1645  });1646.1647.fi1648.1649.IP "" 01650.1651.SS "app\.set(name[, val])"1652Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1653.1654.IP "" 41655.1656.nf16571658app\.set(\'views\', __dirname + \'/views\');1659app\.set(\'views\');1660// => \.\.\.path\.\.\.1661.1662.fi1663.1664.IP "" 01665.1666.P1667Alternatively you may simply access the settings via \fIapp\.settings\fR:1668.1669.IP "" 41670.1671.nf16721673app\.settings\.views1674// => \.\.\.path\.\.\.1675.1676.fi1677.1678.IP "" 01679.1680.SS "app\.enable(name)"1681Enable the given setting \fIname\fR:1682.1683.IP "" 41684.1685.nf16861687app\.enable(\'some arbitrary setting\');1688app\.set(\'some arbitrary setting\');1689// => true16901691app\.enabled(\'some arbitrary setting\');1692// => true1693.1694.fi1695.1696.IP "" 01697.1698.SS "app\.disable(name)"1699Disable the given setting \fIname\fR:1700.1701.IP "" 41702.1703.nf17041705app\.disable(\'some setting\');1706app\.set(\'some setting\');1707// => false17081709app\.disabled(\'some setting\');1710// => false1711.1712.fi1713.1714.IP "" 01715.1716.SS "app\.configure(env|function[, function])"1717Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1718.1719.IP "" 41720.1721.nf17221723app\.configure(function(){1724    // executed for each env1725});17261727app\.configure(\'development\', function(){1728    // executed for \'development\' only1729});1730.1731.fi1732.1733.IP "" 01734.1735.SS "app\.redirect(name, val)"1736For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1737.1738.IP "" 41739.1740.nf17411742app\.redirect(\'google\', \'http://google\.com\');1743.1744.fi1745.1746.IP "" 01747.1748.P1749Now in a route we may call:1750.1751.P1752res\.redirect(\'google\');1753.1754.P1755We may also map dynamic redirects:1756.1757.IP "" 41758.1759.nf17601761app\.redirect(\'comments\', function(req, res){1762    return \'/post/\' + req\.params\.id + \'/comments\';1763});1764.1765.fi1766.1767.IP "" 01768.1769.P1770So 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\.1771.1772.IP "" 41773.1774.nf17751776app\.get(\'/post/:id\', function(req, res){1777    res\.redirect(\'comments\');1778});1779.1780.fi1781.1782.IP "" 01783.1784.SS "app\.error(function)"1785Adds 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:1786.1787.IP "" 41788.1789.nf17901791app\.error(function(err, req, res, next){1792    res\.send(err\.message, 500);1793});1794.1795.fi1796.1797.IP "" 01798.1799.SS "app\.helpers(obj)"1800Registers static view helpers\.1801.1802.IP "" 41803.1804.nf18051806app\.helpers({1807    name: function(first, last){ return first + \', \' + last },1808    firstName: \'tj\',1809    lastName: \'holowaychuk\'1810});1811.1812.fi1813.1814.IP "" 01815.1816.P1817Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1818.1819.IP "" 41820.1821.nf18221823<%= name(firstName, lastName) %>1824.1825.fi1826.1827.IP "" 01828.1829.SS "app\.dynamicHelpers(obj)"1830Registers 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\.1831.1832.IP "" 41833.1834.nf18351836app\.dynamicHelpers({1837    session: function(req, res){1838        return req\.session;1839    }1840});1841.1842.fi1843.1844.IP "" 01845.1846.P1847All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1848.1849.IP "" 41850.1851.nf18521853<%= session\.name %>1854.1855.fi1856.1857.IP "" 01858.1859.SS "app\.mounted(fn)"1860Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1861.1862.IP "" 41863.1864.nf18651866var app = express\.createServer(),1867    blog = express\.createServer();18681869blog\.mounted(function(parent){1870    // parent is app1871    // "this" is blog1872});18731874app\.use(blog);1875.1876.fi1877.1878.IP "" 01879.1880.SS "app\.register(ext, exports)"1881Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:1882.1883.IP "" 41884.1885.nf18861887 app\.register(\'\.html\', require(\'jade\'));1888.1889.fi1890.1891.IP "" 01892.1893.P1894This 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":1895.1896.IP "" 41897.1898.nf18991900 app\.register(\'\.haml\', require(\'haml\-js\'));1901.1902.fi1903.1904.IP "" 01905.1906.P1907For engines that do not comply with the Express specification, we can also wrap their api this way\.1908.1909.IP "" 41910.1911.nf19121913 app\.register(\'\.foo\', {1914     render: function(str, options) {1915         // perhaps their api is1916         // return foo\.toHTML(str, options);1917     }1918 });1919.1920.fi1921.1922.IP "" 01923.1924.SS "app\.listen([port[, host]])"1925Bind 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\.1926.1927.IP "" 41928.1929.nf19301931app\.listen();1932app\.listen(3000);1933app\.listen(3000, \'n\.n\.n\.n\');1934.1935.fi1936.1937.IP "" 01938.1939.P1940The \fIport\fR argument may also be a string representing the path to a unix domain socket:1941.1942.IP "" 41943.1944.nf19451946app\.listen(\'/tmp/express\.sock\');1947.1948.fi1949.1950.IP "" 01951.1952.P1953Then try it out:1954.1955.IP "" 41956.1957.nf19581959$ telnet /tmp/express\.sock1960GET / HTTP/1\.119611962HTTP/1\.1 200 OK1963Content\-Type: text/plain1964Content\-Length: 1119651966Hello World1967.1968.fi1969.1970.IP "" 01971