Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,364 lines · 47.4 KiB · Markdown

Last changed by

docs for previous commitTj Holowaychukbefore adoptionf36d079

History of this file

Take it

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

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 1–4why, one step back
1### Installation
23 $ npm install express4

added quick start to guideTj Holowaychukbefore adoption723774a

lines 5–25why, one step back
5or to access the `express(1)` executable install globally:
67 $ npm install -g express89## Quick Start1011 The quickest way to get started with express is to utilize the executable `express(1)` to generate an application as shown below:1213 Create the app:1415 $ npm install -g express16 $ express /tmp/foo && cd /tmp/foo1718 Install dependencies:1920 $ npm install -d2122 Start the server:2324 $ node app.js25

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 26–73why, one step back
26### Creating A Server
2728 To create an instance of the _express.HTTPServer_, simply invoke the _createServer()_ method. With our instance _app_ we can then define routes based on the HTTP verbs, in this example _app.get()_.2930 var app = require('express').createServer();31 32 app.get('/', function(req, res){33 res.send('hello world');34 });35 36 app.listen(3000);3738### Creating An HTTPS Server3940 To initialize a _express.HTTPSServer_ we do the same as above, however we41 pass an options object, accepting _key_, _cert_ and the others mentioned in node's [https documentation](http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer).42 43 var app = require('express').createServer({ key: ... });4445### Configuration4647Express supports arbitrary environments, such as _production_ and _development_. Developers48can use the _configure()_ method to setup needs required by the current environment. When49_configure()_ is called without an environment name it will be run in _every_ environment 50prior to the environment specific callback.5152In the example below we only _dumpExceptions_, and respond with exception stack traces53in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.54Note the use of _app.router_, which can (optionally) be used to mount the application routes,55otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.5657 app.configure(function(){58 app.use(express.methodOverride());59 app.use(express.bodyParser());60 app.use(app.router);61 });62 63 app.configure('development', function(){64 app.use(express.static(__dirname + '/public'));65 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));66 });67 68 app.configure('production', function(){69 var oneYear = 31557600000;70 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));71 app.use(express.errorHandler());72 });73

docs for multiple envs in app.configure() callsTj Holowaychukbefore adoption45d149c

lines 74–79why, one step back
74For similar environments you may also pass several env strings:
7576 app.configure('stage', 'prod', function(){77 // config78 });79

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 80–110why, one step back
80For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:
8182 app.configure(function(){83 app.set('views', __dirname + '/views');84 app.set('views');85 // => "/absolute/path/to/views"86 87 app.enable('some feature');88 // same as app.set('some feature', true);89 90 app.disable('some feature');91 // same as app.set('some feature', false);92 93 app.enabled('some feature')94 // => false95 });9697To alter the environment we can set the _NODE_ENV_ environment variable, for example:9899 $ NODE_ENV=production node app.js100101This is _very_ important, as many caching mechanisms are _only enabled_ when in production.102103### Settings104105Express supports the following settings out of the box:106107 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.108 * _views_ Root views directory defaulting to **CWD/views**109 * _view engine_ Default view engine name for views rendered without extensions110 * _view options_ An object specifying global view options

docs for "view cache" settingTj Holowaychukbefore adoption805b9ac

line 111why, one step back
111 * _view cache_ Enable view caching (enabled in production)

docs for previous commitTj Holowaychukbefore adoptionf36d079

line 112why, one step back
112 * _charset_ Alter the default charset of "utf-8"

Added "case sensitive routes" option.Tj Holowaychukbefore adoptiond2adcbd

line 113why, one step back
113 * _case sensitive routes_ Enable case-sensitive routing

Added "strict routing" setting for trailing slashesTj Holowaychukbefore adoption6f7075b

line 114why, one step back
114 * _strict routing_ When enabled trailing slashes are no longer ignored

moved jsonp testsTj Holowaychukbefore adoption87bc265

line 115why, one step back
115 * _jsonp callback_ Enable _res.send()_ / _res.json()_ transparent jsonp support

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 116–198why, one step back
116
117### Routing118119Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.120For example we may want to render a user's account for the path _/user/12_, this121can be done by defining the route below. The values associated to the named placeholders 122are available as `req.params`.123124 app.get('/user/:id', function(req, res){125 res.send('user ' + req.params.id);126 });127128A route is simple a string which is compiled to a _RegExp_ internally. For example129when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:130131 \/user\/([^\/]+)\/?132133Regular expression literals may also be passed for complex uses. Since capture134groups with literal _RegExp_'s are anonymous we can access them directly `req.params`. So our first capture group would be _req.params[0]_ and the second would follow as _req.params[1]_.135136 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){137 res.send(req.params);138 });139140Curl requests against the previously defined route:141142 $ curl http://dev:3000/user143 [null,null]144 $ curl http://dev:3000/users145 [null,null]146 $ curl http://dev:3000/users/1147 ["1",null]148 $ curl http://dev:3000/users/1..15149 ["1","15"]150151Below are some route examples, and the associated paths that they152may consume:153154 "/user/:id"155 /user/12156157 "/users/:id?"158 /users/5159 /users160161 "/files/*"162 /files/jquery.js163 /files/javascripts/jquery.js164165 "/file/*.*"166 /files/jquery.js167 /files/javascripts/jquery.js168 169 "/user/:id/:operation?"170 /user/1171 /user/1/edit172 173 "/products.:format"174 /products.json175 /products.xml176177 "/products.:format?"178 /products.json179 /products.xml180 /products181 182 "/user/:id.:format?"183 /user/12184 /user/12.json185186For example we can __POST__ some json, and echo the json back using the _bodyParser_ middleware which will parse json request bodies (as well as others), and place the result in _req.body_:187188 var express = require('express')189 , app = express.createServer();190191 app.use(express.bodyParser());192193 app.post('/', function(req, res){194 res.send(req.body);195 });196197 app.listen(3000);198

docsTj Holowaychukbefore adoption6106188

line 199why, one step back
199Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use _'/user/:id([0-9]+)'_ which will _not_ match unless the placeholder value contains only digits.

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 200–267why, one step back
200
201### Passing Route Control202203We may pass control to the next _matching_ route, by calling the _third_ argument,204the _next()_ function. When a match cannot be made, control is passed back to Connect,205and middleware continue to be invoked in the order that they are added via _use()_. The same is true for several routes which have the same path defined, they will simply be executed in order until one does _not_ call _next()_ and decides to respond.206207 app.get('/users/:id?', function(req, res, next){208 var id = req.params.id;209 if (id) {210 // do something211 } else {212 next();213 }214 });215 216 app.get('/users', function(req, res){217 // do something else218 });219220The _app.all()_ method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to _req.user_.221222 var express = require('express')223 , app = express.createServer();224225 var users = [{ name: 'tj' }];226227 app.all('/user/:id/:op?', function(req, res, next){228 req.user = users[req.params.id];229 if (req.user) {230 next();231 } else {232 next(new Error('cannot find user ' + req.params.id));233 }234 });235236 app.get('/user/:id', function(req, res){237 res.send('viewing ' + req.user.name);238 });239240 app.get('/user/:id/edit', function(req, res){241 res.send('editing ' + req.user.name);242 });243244 app.put('/user/:id', function(req, res){245 res.send('updating ' + req.user.name);246 });247248 app.get('*', function(req, res){249 res.send('what???', 404);250 });251252 app.listen(3000); 253254### Middleware255256Middleware via [Connect](http://github.com/senchalabs/connect) can be257passed to _express.createServer()_ as you would with a regular Connect server. For example:258259 var express = require('express');260261 var app = express.createServer(262 express.logger()263 , express.bodyParser()264 );265266Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.267

Merge pull request #671 from jpalardy/patch-1TJ Holowaychukbefore adoptionc24b2fa

line 268why, one step back
268 app.use(express.logger({ format: ':method :url' }));

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 269–280why, one step back
269
270Typically with connect middleware you would _require('connect')_ like so:271272 var connect = require('connect');273 app.use(connect.logger());274 app.use(connect.bodyParser());275276This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:277278 app.use(express.logger());279 app.use(express.bodyParser());280

added better middleware docs and use-casesTj Holowaychukbefore adoption8d6f167

lines 281–307why, one step back
281Middleware ordering is important, when Connect receives a request the _first_ middleware we pass to _createServer()_ or _use()_ is executed with three parameters, _request_, _response_, and a callback function usually named _next_. When _next()_ is invoked the second middleware will then have it's turn and so on. This is important to note because many middleware depend on each other, for example _methodOverride()_ checks _req.body._method_ for the HTTP method override, however _bodyParser()_ parses the request body and populates _req.body_. Another example of this is cookie parsing and session support, we must first _use()_ _cookieParser()_ followed by _session()_.
282283Many Express applications may contain the line _app.use(app.router)_, while this may appear strange, it's simply the middleware function that contains all defined routes, and performs route lookup based on the current request url and HTTP method. Express allows you to position this middleware, though by default it will be added to the bottom. By positioning the router, we can alter middleware precedence, for example we may want to add error reporting as the _last_ middleware so that any exception passed to _next()_ will be handled by it, or perhaps we want static file serving to have low precedence, allowing our routes to intercept requests to a static file to count downloads etc. This may look a little like below284285 app.use(express.logger(...));286 app.use(express.bodyParser(...));287 app.use(express.cookieParser(...));288 app.use(express.session(...));289 app.use(app.router);290 app.use(express.static(...));291 app.use(express.errorHandler(...));292293First we add _logger()_ so that it may wrap node's _req.end()_ method, providing us with response-time data. Next the request's body will be parsed (if any), followed by cookie parsing and session support, meaning _req.session_ will be defined by the time we hit our routes in _app.router_. If a request such as _GET /javascripts/jquery.js_ is handled by our routes, and we do not call _next()_ then the _static()_ middleware will never see this request, however if were to define a route as shown below, we can record stats, refuse downloads, consume download credits etc.294295 var downloads = {};296297 app.use(app.router);298 app.use(express.static(__dirname + '/public'));299300 app.get('/*', function(req, res, next){301 var file = req.params[0];302 downloads[file] = downloads[file] || 0;303 downloads[file]++;304 next();305 });306307

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 308–378why, one step back
308### Route Middleware
309310Routes 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.311312Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 313314 app.get('/user/:id', function(req, res, next){315 loadUser(req.params.id, function(err, user){316 if (err) return next(err);317 res.send('Viewing user ' + user.name);318 });319 });320321To 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. 322323 function loadUser(req, res, next) {324 // You would fetch your user from the db325 var user = users[req.params.id];326 if (user) {327 req.user = user;328 next();329 } else {330 next(new Error('Failed to load user ' + req.params.id));331 }332 }333 334 app.get('/user/:id', loadUser, function(req, res){335 res.send('Viewing user ' + req.user.name);336 });337338Multiple 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.339340 function andRestrictToSelf(req, res, next) {341 req.authenticatedUser.id == req.user.id342 ? next()343 : next(new Error('Unauthorized'));344 }345 346 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){347 res.send('Editing user ' + req.user.name);348 });349350Keeping in mind that middleware are simply functions, we can define function that _returns_ the middleware in order to create a more expressive and flexible solution as shown below.351352 function andRestrictTo(role) {353 return function(req, res, next) {354 req.authenticatedUser.role == role355 ? next()356 : next(new Error('Unauthorized'));357 }358 }359 360 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){361 res.send('Deleted user ' + req.user.name);362 });363364Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.365366 var a = [middleware1, middleware2]367 , b = [middleware3, middleware4]368 , all = [a, b];369 370 app.get('/foo', a, function(){});371 app.get('/bar', a, function(){});372 373 app.get('/', a, middleware3, middleware4, function(){});374 app.get('/', a, b, function(){});375 app.get('/', all, function(){});376377For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.378

docs for next("route"). Closes #650Tj Holowaychukbefore adoption2648302

lines 379–380why, one step back
379There are times when we may want to "skip" passed remaining route middleware, but continue matching subsequent routes. To do this we invoke `next()` with the string "route" `next('route')`. If no remaining routes match the request url then Express will respond with 404 Not Found.
380

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 381–424why, one step back
381### HTTP Methods
382383We have seen _app.get()_ a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as _app.post()_, _app.del()_, etc.384385 A common example for _POST_ 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.386 387 <form method="post" action="/">388 <input type="text" name="user[name]" />389 <input type="text" name="user[email]" />390 <input type="submit" value="Submit" />391 </form>392393By default Express does not know what to do with this request body, so we should add the _bodyParser_ middleware, which will parse _application/x-www-form-urlencoded_ and _application/json_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:394395 app.use(express.bodyParser());396397Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.398399 app.post('/', function(req, res){400 console.log(req.body.user);401 res.redirect('back');402 });403404When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyParser_ so that it can utilize it's _req.body_ containing the form values.405406 app.use(express.bodyParser());407 app.use(express.methodOverride());408409The 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 _PUT_ and _DELETE_ can still be accessed by clients which can use them directly, although _methodOverride_ provides a great solution for forms. Below shows what the usage of _PUT_ might look like:410411 <form method="post" action="/">412 <input type="hidden" name="_method" value="put" />413 <input type="text" name="user[name]" />414 <input type="text" name="user[email]" />415 <input type="submit" value="Submit" /> 416 </form>417418 app.put('/', function(){419 console.log(req.body.user);420 res.redirect('back');421 });422423### Error Handling424

removed old error handling docsTj Holowaychukbefore adoption7d53bb4

lines 425–433why, one step back
425 Error handling middleware are simply middleware with an arity of 4, aka
426 the signature _(err, req, res, next)_. When you _next(err)_ an error,427 only these middleware are executed and have a chance to respond. For example:428 429 app.use(app.bodyParser());430 app.use(app.methodOverride());431 app.use(app.router);432 app.use(function(err, req, res, next){433 res.send('Internal Server Error', 500);

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 434–577why, one step back
434 });
435436### Route Param Pre-conditions437438Route param 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 _/user/:id_, we might typically do something like below:439440 app.get('/user/:userId', function(req, res, next){441 User.get(req.params.userId, function(err, user){442 if (err) return next(err);443 res.send('user ' + user.name);444 });445 }); 446447With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.448449 app.param('userId', function(req, res, next, id){450 User.get(id, function(err, user){451 if (err) return next(err);452 if (!user) return next(new Error('failed to find user'));453 req.user = user;454 next();455 });456 });457458Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:459460 app.get('/user/:userId', function(req, res){461 res.send('user ' + req.user.name);462 });463464### View Rendering465466View filenames take the form "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name467of the module that will be required. For example the view _layout.ejs_ will468tell the view system to _require('ejs')_, the module being loaded must export the method _exports.compile(str, options)_, and return a _Function_ to comply with Express. To alter this behaviour469_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.470471Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,472and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 473the _body_ local variable in _layout.jade_.474475 app.get('/', function(req, res){476 res.render('index.jade', { title: 'My Site' });477 });478479The new _view engine_ setting allows us to specify our default template engine,480so for example when using jade we could set:481482 app.set('view engine', 'jade');483484Allowing us to render with:485486 res.render('index');487488vs:489490 res.render('index.jade');491492When _view engine_ is set, extensions are entirely optional, however we can still493mix and match template engines:494495 res.render('another-page.ejs');496497Express also provides the _view options_ setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:498499 app.set('view options', {500 layout: false501 });502503Which can then be overridden within the _res.render()_ call if need be:504505 res.render('myview.ejs', { layout: true });506507When an alternate layout is required, we may also specify a path. For example if we have _view engine_ set to _jade_ and a file named _./views/mylayout.jade_ we can simply pass:508509 res.render('page', { layout: 'mylayout' });510511Otherwise we must specify the extension:512513 res.render('page', { layout: 'mylayout.jade' });514515These paths may also be absolute:516517 res.render('page', { layout: __dirname + '/../../mylayout.jade' });518519A good example of this is specifying custom _ejs_ opening and closing tags:520521 app.set('view options', {522 open: '{{',523 close: '}}'524 });525526### View Partials527528The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating529in a view to display comments, we could use partial collection:530531 partial('comment', { collection: comments });532533If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:534535 partial('comment', comments);536537When using the partial collection support a few "magic" locals are provided538for free:539540 * _firstInCollection_ true if this is the first object541 * _indexInCollection_ index of the object in the collection542 * _lastInCollection_ true if this is the last object543 * _collectionLength_ length of the collection544545Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well. So for example if we were to render a blog post with _partial('blog/post', post)_ it would generate the _post_ local, but the view calling this function had the local _user_, it would be available to the _blog/post_ view as well.546547For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).548549__NOTE:__ be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead.550551### View Lookup552553View lookup is performed relative to the parent view, for example if we had a page view named _views/user/list.jade_, and within that view we did _partial('edit')_ it would attempt to load _views/user/edit.jade_, whereas _partial('../messages')_ would load _views/messages.jade_.554555The view system also allows for index templates, allowing you to have a directory of the same name. For example within a route we may have _res.render('users')_ either _views/users.jade_, or _views/users/index.jade_.556557When utilizing index views as shown above, we may reference _views/users/index.jade_ from a view in the same directory by _partial('users')_, and the view system will try _../users/index_, preventing us from needing to call _partial('index')_.558559### Template Engines560561Below are a few template engines commonly used with Express:562563 * [Haml](http://github.com/visionmedia/haml.js) haml implementation564 * [Jade](http://jade-lang.com) haml.js successor565 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript566 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating567 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node568569### Session Support570571Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieParser_ middleware place above it, which will parse and populate cookie data to _req.cookies_.572573 app.use(express.cookieParser());574 app.use(express.session({ secret: "keyboard cat" }));575576By default the _session_ middleware uses the memory store bundled with Connect, however many implementations exist. For example [connect-redis](http://github.com/visionmedia/connect-redis) supplies a [Redis](http://code.google.com/p/redis/) session store and can be used as shown below:577

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4

line 578why, one step back
578 var RedisStore = require('connect-redis')(express);

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 579–583why, one step back
579 app.use(express.cookieParser());
580 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));581582Now the _req.session_ and _req.sessionStore_ properties will be accessible to all routes and subsequent middleware. Properties on _req.session_ are automatically saved on a response, so for example if we wish to shopping cart data:583

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4

line 584why, one step back
584 var RedisStore = require('connect-redis')(express);

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 585–715why, one step back
585 app.use(express.bodyParser());
586 app.use(express.cookieParser());587 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));588589 app.post('/add-to-cart', function(req, res){590 // Perhaps we posted several items with a form591 // (use the bodyParser() middleware for this)592 var items = req.body.items;593 req.session.items = items;594 res.redirect('back');595 });596597 app.get('/add-to-cart', function(req, res){598 // When redirected back to GET /add-to-cart599 // we could check req.session.items && req.session.items.length600 // to print out a message601 if (req.session.items && req.session.items.length) {602 req.flash('info', 'You have %s items in your cart', req.session.items.length);603 }604 res.render('shopping-cart');605 });606607The _req.session_ object also has methods such as _Session#touch()_, _Session#destroy()_, _Session#regenerate()_ among others to maintain and manipulate sessions. For more information view the [Connect Session](http://senchalabs.github.com/connect/middleware-session.html) documentation.608609### Migration Guide610611 Express 1.x developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application to work with Express 2.x, Connect 1.x, and Node 0.4.x.612613### req.header(key[, defaultValue])614615Get the case-insensitive request header _key_, with optional _defaultValue_:616617 req.header('Host');618 req.header('host');619 req.header('Accept', '*/*');620621The _Referrer_ and _Referer_ header fields are special-cased, either will work:622623 // sent Referrer: http://google.com624625 req.header('Referer');626 // => "http://google.com"627628 req.header('Referrer');629 // => "http://google.com"630631### req.accepts(type)632633Check if the _Accept_ header is present, and includes the given _type_.634635When the _Accept_ header is not present _true_ is returned. Otherwise636the given _type_ is matched by an exact match, and then subtypes. You637may pass the subtype such as "html" which is then converted internally638to "text/html" using the mime lookup table.639640 // Accept: text/html641 req.accepts('html');642 // => true643644 // Accept: text/*; application/json645 req.accepts('html');646 req.accepts('text/html');647 req.accepts('text/plain');648 req.accepts('application/json');649 // => true650651 req.accepts('image/png');652 req.accepts('png');653 // => false654655### req.is(type)656657Check if the incoming request contains the _Content-Type_658header field, and it contains the give mime _type_.659 660 // With Content-Type: text/html; charset=utf-8661 req.is('html');662 req.is('text/html');663 // => true664 665 // When Content-Type is application/json666 req.is('json');667 req.is('application/json');668 // => true669 670 req.is('html');671 // => false672 673Ad-hoc callbacks can also be registered with Express, to perform674assertions again the request, for example if we need an expressive675way to check if our incoming request is an image, we can register _"an image"_676callback:677 678 app.is('an image', function(req){679 return 0 == req.headers['content-type'].indexOf('image');680 });681 682Now within our route callbacks, we can use to to assert content types683such as _"image/jpeg"_, _"image/png"_, etc.684 685 app.post('/image/upload', function(req, res, next){686 if (req.is('an image')) {687 // do something688 } else {689 next();690 }691 });692693Keep in mind this method is _not_ limited to checking _Content-Type_, you694can perform any request assertion you wish.695696Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:697698 req.is('image/*');699700We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.701702 req.is('*/json');703704### req.param(name[, default])705706Return the value of param _name_ when present or _default_.707708 - Checks route params (_req.params_), ex: /user/:id709 - Checks query string params (_req.query_), ex: ?id=12710 - Checks urlencoded body params (_req.body_), ex: id=12711712To utilize urlencoded request bodies, _req.body_713should be an object. This can be done by using714the _express.bodyParser middleware.715

docs for req.get()Tj Holowaychukbefore adoption6bb100d

lines 716–726why, one step back
716### req.get(field, param)
717718 Get _field_'s _param_ value, defaulting to '' when the _param_719 or _field_ is not present.720721 req.get('content-disposition', 'filename');722 // => "something.png"723724 req.get('Content-Type', 'boundary');725 // => "--foo-bar-baz"726

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 727–832why, one step back
727### req.flash(type[, msg])
728729Queue flash _msg_ of the given _type_.730731 req.flash('info', 'email sent');732 req.flash('error', 'email delivery failed');733 req.flash('info', 'email re-sent');734 // => 2735736 req.flash('info');737 // => ['email sent', 'email re-sent']738739 req.flash('info');740 // => []741742 req.flash();743 // => { error: ['email delivery failed'], info: [] }744745Flash notification message may also utilize formatters, by default only the %s string formatter is available:746747 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);748749### req.isXMLHttpRequest750751Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header752to see if it was issued by an _XMLHttpRequest_:753754 req.xhr755 req.isXMLHttpRequest756757### res.header(key[, val])758759Get or set the response header _key_.760761 res.header('Content-Length');762 // => undefined763764 res.header('Content-Length', 123);765 // => 123766 767 res.header('Content-Length');768 // => 123769770### res.charset771772Sets the charset for subsequent `Content-Type` header fields. For example `res.send()` and `res.render()` default to "utf8", so we may explicitly set the charset before rendering a template:773774 res.charset = 'ISO-8859-1';775 res.render('users');776777or before responding with `res.send()`:778779 res.charset = 'ISO-8859-1';780 res.send(str);781782or with node's `res.end()`:783784 res.charset = 'ISO-8859-1';785 res.header('Content-Type', 'text/plain');786 res.end(str);787788### res.contentType(type)789790Sets the _Content-Type_ response header to the given _type_.791792 var filename = 'path/to/image.png';793 res.contentType(filename);794 // Content-Type is now "image/png"795796A literal _Content-Type_ works as well:797798 res.contentType('application/json');799800Or simply the extension without leading `.`:801802 res.contentType('json');803804### res.attachment([filename])805806Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.807808 res.attachment('path/to/my/image.png');809810### res.sendfile(path[, options[, callback]])811812Used by `res.download()` to transfer an arbitrary file. 813814 res.sendfile('path/to/my.file');815816This method accepts an optional callback which is called when817an error occurs, or when the transfer is complete. By default failures call `next(err)`, however when a callback is supplied you must do this explicitly, or act on the error.818819 res.sendfile(path, function(err){820 if (err) {821 next(err);822 } else {823 console.log('transferred %s', path);824 }825 });826827Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:828829 res.sendfile(path, { bufferSize: 1024 }, function(err){830 // handle831 });832

docsTj Holowaychukbefore adoption236a412

line 833why, one step back
833### res.download(file[, filename[, callback[, callback2]]])

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 834–844why, one step back
834
835Transfer the given _file_ as an attachment with optional alternative _filename_.836837 res.download('path/to/image.png');838 res.download('path/to/image.png', 'foo.png');839840This is equivalent to:841842 res.attachment(file);843 res.sendfile(file);844

docsTj Holowaychukbefore adoption236a412

line 845why, one step back
845An optional callback may be supplied as either the second or third argument, which is passed to _res.sendfile()_. Within this callback you may still respond, as the header has not been sent.

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 846–848why, one step back
846
847 res.download(path, 'expenses.doc', function(err){848 // handle

docsTj Holowaychukbefore adoption236a412

lines 849–856why, one step back
849 });
850851An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.852853 res.download(path, function(err){854 // error or finished855 }, function(err){856 // connection related error

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 857–876why, one step back
857 });
858859### res.send(body|status[, headers|status[, status]])860861The _res.send()_ method is a high level response utility allowing you to pass862objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:863864 res.send(new Buffer('wahoo'));865 res.send({ some: 'json' });866 res.send('<p>some html</p>');867 res.send('Sorry, cant find that', 404);868 res.send('text', { 'Content-Type': 'text/plain' }, 201);869 res.send(404);870871By default the _Content-Type_ response header is set, however if explicitly872assigned through `res.send()` or previously with `res.header()` or `res.contentType()`873it will not be set again.874875Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.876

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 877–888why, one step back
877### res.json(obj[, headers|status[, status]])
878879 Send a JSON response with optional _headers_ and _status_. This method880 is ideal for JSON-only APIs, however _res.send(obj)_ will send JSON as881 well, though not ideal for cases when you want to send for example a string882 as JSON, since the default for _res.send(string)_ is text/html.883884 res.json(null);885 res.json({ user: 'tj' });886 res.json('oh noes!', 500);887 res.json('I dont have that', 404);888

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 889–904why, one step back
889### res.redirect(url[, status])
890891Redirect to the given _url_ with a default response _status_ of 302.892893 res.redirect('/', 301);894 res.redirect('/account');895 res.redirect('http://google.com');896 res.redirect('home');897 res.redirect('back');898899Express supports "redirect mapping", which by default provides _home_, and _back_.900The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes901the "home" setting and defaults to "/".902903### res.cookie(name, val[, options])904

docsTj Holowaychukbefore adoption6815feb

lines 905–906why, one step back
905Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc. The _path_ option defaults to the app's "home" setting, which
906is typically "/".

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 907–914why, one step back
907
908 // "Remember me" for 15 minutes 909 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });910911The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:912913 res.cookie('rememberme', 'yes', { maxAge: 900000 });914

doc typoTj Holowaychukbefore adoption62df63d

line 915why, one step back
915To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 916–922why, one step back
916
917 app.use(express.cookieParser());918 919 app.get('/', function(req, res){920 // use req.cookies.rememberme921 });922

Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d

line 923why, one step back
923### res.clearCookie(name[, options])

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

line 924why, one step back
924

docsTj Holowaychukbefore adoption6815feb

lines 925–926why, one step back
925Clear cookie _name_ by setting "expires" far in the past. Much like
926_res.cookie()_ the _path_ option also defaults to the "home" setting.

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 927–940why, one step back
927
928 res.clearCookie('rememberme');929930### res.render(view[, options[, fn]])931932Render _view_ with the given _options_ and optional callback _fn_.933When a callback function is given a response will _not_ be made934automatically, however otherwise a response of _200_ and _text/html_ is given.935936The _options_ passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:937938 var user = { name: 'tj' };939 res.render('index', { layout: false, user: user });940

Added docs for `status` option special-case. Closes #739Tj Holowaychukbefore adoptionc0aab36

lines 941–949why, one step back
941This _options_ object is also considered an "options" object. For example
942when you pass the _status_ local, it's not only available to the view, it943sets the response status to this number. This is also useful if a template944engine accepts specific options, such as _debug_, or _compress_. Below945is an example of how one might render an error page, passing the _status_ for946display, as well as it setting _res.statusCode_.947948 res.render('error', { status: 500, message: 'Internal Server Error' });949

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 950–1162why, one step back
950### res.partial(view[, options])
951952Render _view_ partial with the given _options_. This method is always available953to the view as a local variable.954955- _object_ the object named by _as_ or derived from the view name956- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.957 * as: 'something' will add the _something_ local variable958 * as: this will use the collection value as the template context959 * as: global will merge the collection value's properties with _locals_960961- _collection_ Array of objects, the name is derived from the view name itself. 962 For example _video.html_ will have a object _video_ available to it.963964The following are equivalent, and the name of collection value when passed965to the partial will be _movie_ as derived from the name.966967 partial('theatre/movie.jade', { collection: movies });968 partial('theatre/movie.jade', movies);969 partial('movie.jade', { collection: movies });970 partial('movie.jade', movies);971 partial('movie', movies);972 // In view: movie.director973974To change the local from _movie_ to _video_ we can use the "as" option:975976 partial('movie', { collection: movies, as: 'video' });977 // In view: video.director978979Also we can make our movie the value of _this_ within our view so that instead980of _movie.director_ we could use _this.director_.981982 partial('movie', { collection: movies, as: this });983 // In view: this.director984985Another alternative is to "expand" the properties of the collection item into986pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:987988 partial('movie', { collection: movies, as: global });989 // In view: director990991This same logic applies to a single partial object usage:992993 partial('movie', { object: movie, as: this });994 // In view: this.director995996 partial('movie', { object: movie, as: global });997 // In view: director998999 partial('movie', { object: movie, as: 'video' });1000 // In view: video.director10011002 partial('movie', { object: movie });1003 // In view: movie.director10041005When a non-collection (does _not_ have _.length_) is passed as the second argument, it is assumed to be the _object_, after which the object's local variable name is derived from the view name:10061007 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1008 partial('movie', movie)1009 // => In view: movie.director10101011The exception of this, is when a "plain" object, aka "{}" or "new Object" is passed, which is considered an object with local variable. For example some may expect a "movie" local with the following, however since it is a plain object "director" and "title" are simply locals:10121013 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1014 partial('movie', movie)10151016For cases like this where passing a plain object is desired, simply assign it to a key, or use the `object` key which will use the filename-derived variable name. The examples below are equivalent:10171018 partial('movie', { locals: { movie: movie }})1019 partial('movie', { movie: movie })1020 partial('movie', { object: movie })10211022This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:10231024 app.get('/users', function(req, res){1025 if (req.xhr) {1026 // respond with the each user in the collection1027 // passed to the "user" view1028 res.partial('user', users);1029 } else {1030 // respond with layout, and users page1031 // which internally does partial('user', users)1032 // along with other UI1033 res.render('users', { users: users });1034 }1035 });10361037### res.local(name[, val])10381039Get or set the given local variable _name_. The locals built up for a response are applied to those given to the view rendering methods such as `res.render()`.10401041 app.all('/movie/:id', function(req, res, next){1042 Movie.get(req.params.id, function(err, movie){1043 // Assigns res.locals.movie = movie1044 res.local('movie', movie);1045 });1046 });1047 1048 app.get('/movie/:id', function(req, res){1049 // movie is already a local, however we1050 // can pass more if we wish1051 res.render('movie', { displayReviews: true });1052 });10531054### res.locals(obj)10551056 Assign several locals with the given _obj_. The following are equivalent:1057 1058 res.local('foo', bar);1059 res.local('bar', baz);10601061 res.locals({ foo: bar, bar, baz });10621063### app.set(name[, val])10641065Apply an application level setting _name_ to _val_, or1066get the value of _name_ when _val_ is not present:10671068 app.set('views', __dirname + '/views');1069 app.set('views');1070 // => ...path...10711072Alternatively you may simply access the settings via _app.settings_:10731074 app.settings.views1075 // => ...path...10761077### app.enable(name)10781079Enable the given setting _name_:10801081 app.enable('some arbitrary setting');1082 app.set('some arbitrary setting');1083 // => true10841085 app.enabled('some arbitrary setting');1086 // => true10871088### app.enabled(name)10891090Check if setting _name_ is enabled:10911092 app.enabled('view cache');1093 // => false10941095 app.enable('view cache');1096 app.enabled('view cache');1097 // => true10981099### app.disable(name)11001101Disable the given setting _name_:11021103 app.disable('some setting');1104 app.set('some setting');1105 // => false1106 1107 app.disabled('some setting');1108 // => false11091110### app.disabled(name)11111112Check if setting _name_ is disabled:11131114 app.enable('view cache');11151116 app.disabled('view cache');1117 // => false11181119 app.disable('view cache');1120 app.disabled('view cache');1121 // => true11221123### app.configure(env|function[, function])11241125Define a callback function for the given _env_ (or all environments) with callback _function_:11261127 app.configure(function(){1128 // executed for each env1129 });11301131 app.configure('development', function(){1132 // executed for 'development' only1133 });11341135### app.redirect(name, val)11361137For use with _res.redirect()_ we can map redirects at the application level as shown below:11381139 app.redirect('google', 'http://google.com');11401141Now in a route we may call:11421143 res.redirect('google');11441145We may also map dynamic redirects:11461147 app.redirect('comments', function(req, res){1148 return '/post/' + req.params.id + '/comments';1149 });11501151So now we may do the following, and the redirect will dynamically adjust to1152the context of the request. If we called this route with _GET /post/12_ our1153redirect _Location_ would be _/post/12/comments_.11541155 app.get('/post/:id', function(req, res){1156 res.redirect('comments');1157 });11581159When mounted, _res.redirect()_ will respect the mount-point. For example if a blog app is mounted at _/blog_, the following will redirect to _/blog/posts_:11601161 res.redirect('/posts');1162

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

line 1163why, one step back
1163### app.locals(obj)

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

line 1164why, one step back
1164

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

line 1165why, one step back
1165Registers static view locals.

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

line 1166why, one step back
1166

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

line 1167why, one step back
1167 app.locals({

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 1168–1181why, one step back
1168 name: function(first, last){ return first + ', ' + last }
1169 , firstName: 'tj'1170 , lastName: 'holowaychuk'1171 });11721173Our view could now utilize the _firstName_ and _lastName_ variables,1174as well as the _name()_ function exposed.11751176 <%= name(firstName, lastName) %>11771178Express also provides a few locals by default:11791180 - `settings` the app's settings object1181 - `filename` the view's filename

docsTj Holowaychukbefore adoption885fb1f

line 1182why, one step back
1182 - `layout(path)` specify the layout from within a view

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

line 1183why, one step back
1183

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

line 1184why, one step back
1184### app.dynamicLocals(obj)

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

line 1185why, one step back
1185

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

line 1186why, one step back
1186Registers dynamic view locals. Dynamic locals

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

line 1187why, one step back
1187are simply functions which accept _req_, _res_, and are

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

line 1188why, one step back
1188evaluated against the _Server_ instance before a view is rendered, and are unique to that specific request. The _return value_ of this function

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 1189–1190why, one step back
1189becomes the local variable it is associated with.
1190

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

line 1191why, one step back
1191 app.dynamicLocals({

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 1192–1200why, one step back
1192 session: function(req, res){
1193 return req.session;1194 }1195 });11961197All views would now have _session_ available so that session data can be accessed via _session.name_ etc:11981199 <%= session.name %>1200

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 1201–1205why, one step back
1201### app.lookup
12021203 The _app.lookup_ http methods returns an array of callback functions1204 associated with the given _path_.1205

docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed

line 1206why, one step back
1206 Suppose we define the following routes:

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 1207–1209why, one step back
1207
1208 app.get('/user/:id', function(){});1209 app.put('/user/:id', function(){});

docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed

line 1210why, one step back
1210 app.get('/user/:id/:op?', function(){});

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 1211–1218why, one step back
1211
1212 We can utilize this lookup functionality to check which routes1213 have been defined, which can be extremely useful for higher level1214 frameworks built on Express.12151216 app.lookup.get('/user/:id');1217 // => [Function]1218

docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed

line 1219why, one step back
1219 app.lookup.get('/user/:id/:op?');

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 1220–1236why, one step back
1220 // => [Function]
12211222 app.lookup.put('/user/:id');1223 // => [Function]12241225 app.lookup.all('/user/:id');1226 // => [Function, Function]12271228 app.lookup.all('/hey');1229 // => []12301231 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1232 without a callback, as a shortcut, for example the following are1233 equivalent:1234 1235 app.lookup.get('/user');1236 app.get('/user');

docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed

line 1237why, one step back
1237

more docsTj Holowaychukbefore adoption6230ec5

lines 1238–1253why, one step back
1238 Each function returned has the following properties:
1239 1240 var fn = app.get('/user/:id/:op?')[0];12411242 fn.regexp1243 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12441245 fn.keys1246 // => ['id', 'op']12471248 fn.path1249 // => '/user/:id/:op?'12501251 fn.method1252 // => 'GET'1253

docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed

lines 1254–1281why, one step back
1254### app.match
12551256 The _app.match_ http methods return an array of callback functions1257 which match the given _url_, which may include a query string etc. This1258 is useful when you want reflect on which routes have the opportunity to1259 respond.12601261 Suppose we define the following routes:12621263 app.get('/user/:id', function(){});1264 app.put('/user/:id', function(){});1265 app.get('/user/:id/:op?', function(){});12661267 Our match against __GET__ will return two functions, since the _:op_1268 in our second route is optional.12691270 app.match.get('/user/1');1271 // => [Function, Function]12721273 This second call returns only the callback for _/user/:id/:op?_.12741275 app.match.get('/user/23/edit');1276 // => [Function]12771278 We can also use _all()_ to disregard the http method:12791280 app.match.all('/user/20');1281 // => [Function, Function, Function]

more docsTj Holowaychukbefore adoption6230ec5

lines 1282–1294why, one step back
1282
1283 Each function matched has the following properties:1284 1285 var fn = app.match.get('/user/23/edit')[0];12861287 fn.keys1288 // => ['id', 'op']12891290 fn.params1291 // => { id: '23', op: 'edit' }12921293 fn.method1294 // => 'GET'

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

line 1295why, one step back
1295

Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478

lines 1296–1364why, one step back
1296### app.mounted(fn)
12971298Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.12991300 var app = express.createServer(),1301 blog = express.createServer();1302 1303 blog.mounted(function(parent){1304 // parent is app1305 // "this" is blog1306 });1307 1308 app.use(blog);13091310### app.register(ext, exports)13111312Register the given template engine _exports_1313as _ext_. For example we may wish to map ".html"1314files to jade:13151316 app.register('.html', require('jade'));13171318This is also useful for libraries that may not1319match extensions correctly. For example my haml.js1320library is installed from npm as "hamljs" so instead1321of layout.hamljs, we can register the engine as ".haml":13221323 app.register('.haml', require('haml-js'));13241325For engines that do not comply with the Express1326specification, we can also wrap their api this way. Below1327we map _.md_ to render markdown files, rendering the html once1328since it will not change on subsequent calls, and support local substitution1329in the form of "{name}".13301331 app.register('.md', {1332 compile: function(str, options){1333 var html = md.toHTML(str);1334 return function(locals){1335 return html.replace(/\{([^}]+)\}/g, function(_, name){1336 return locals[name];1337 });1338 };1339 }1340 });13411342### app.listen([port[, host]])13431344Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1345connections will be accepted via _INADDR_ANY_.13461347 app.listen();1348 app.listen(3000);1349 app.listen(3000, 'n.n.n.n');13501351The _port_ argument may also be a string representing the path to a unix domain socket:13521353 app.listen('/tmp/express.sock');13541355Then try it out:13561357 $ telnet /tmp/express.sock1358 GET / HTTP/1.113591360 HTTP/1.1 200 OK1361 Content-Type: text/plain1362 Content-Length: 111363 1364 Hello World