Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,366 lines · 47.6 KiB · Markdown

Last changed by

misc refactoringTj Holowaychukbefore adoption77d8823

History of this file

Take it

The walk stopped after 200 commits: lines older than 723774a point at it.

added quick start to guideTj Holowaychukbefore adoption723774a

lines 1–73why, one step back
1### Installation
23 $ npm install express45or 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.js2526### Creating A Server2728 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

added quick start to guideTj Holowaychukbefore adoption723774a

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 cache_ Enable view caching (enabled in production)

docs for previous commitTj Holowaychukbefore adoptiond250bf9

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

added quick start to guideTj Holowaychukbefore adoption723774a

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

Added "strict routing" setting for trailing slashesTj Holowaychukbefore adoption6f7075b

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

moved jsonp testsTj Holowaychukbefore adoption87bc265

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 115–247why, one step back
115
116### Routing117118Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.119For example we may want to render a user's account for the path _/user/12_, this120can be done by defining the route below. The values associated to the named placeholders 121are available as `req.params`.122123 app.get('/user/:id', function(req, res){124 res.send('user ' + req.params.id);125 });126127A route is simple a string which is compiled to a _RegExp_ internally. For example128when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:129130 \/user\/([^\/]+)\/?131132Regular expression literals may also be passed for complex uses. Since capture133groups 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]_.134135 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){136 res.send(req.params);137 });138139Curl requests against the previously defined route:140141 $ curl http://dev:3000/user142 [null,null]143 $ curl http://dev:3000/users144 [null,null]145 $ curl http://dev:3000/users/1146 ["1",null]147 $ curl http://dev:3000/users/1..15148 ["1","15"]149150Below are some route examples, and the associated paths that they151may consume:152153 "/user/:id"154 /user/12155156 "/users/:id?"157 /users/5158 /users159160 "/files/*"161 /files/jquery.js162 /files/javascripts/jquery.js163164 "/file/*.*"165 /files/jquery.js166 /files/javascripts/jquery.js167 168 "/user/:id/:operation?"169 /user/1170 /user/1/edit171 172 "/products.:format"173 /products.json174 /products.xml175176 "/products.:format?"177 /products.json178 /products.xml179 /products180 181 "/user/:id.:format?"182 /user/12183 /user/12.json184185For 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_:186187 var express = require('express')188 , app = express.createServer();189190 app.use(express.bodyParser());191192 app.post('/', function(req, res){193 res.send(req.body);194 });195196 app.listen(3000);197198Typically 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.199200### Passing Route Control201202We may pass control to the next _matching_ route, by calling the _third_ argument,203the _next()_ function. When a match cannot be made, control is passed back to Connect,204and 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.205206 app.get('/users/:id?', function(req, res, next){207 var id = req.params.id;208 if (id) {209 // do something210 } else {211 next();212 }213 });214 215 app.get('/users', function(req, res){216 // do something else217 });218219The _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_.220221 var express = require('express')222 , app = express.createServer();223224 var users = [{ name: 'tj' }];225226 app.all('/user/:id/:op?', function(req, res, next){227 req.user = users[req.params.id];228 if (req.user) {229 next();230 } else {231 next(new Error('cannot find user ' + req.params.id));232 }233 });234235 app.get('/user/:id', function(req, res){236 res.send('viewing ' + req.user.name);237 });238239 app.get('/user/:id/edit', function(req, res){240 res.send('editing ' + req.user.name);241 });242243 app.put('/user/:id', function(req, res){244 res.send('updating ' + req.user.name);245 });246247 app.get('*', function(req, res){

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 248why, one step back
248 res.send(404, 'what???');

added quick start to guideTj Holowaychukbefore adoption723774a

lines 249–264why, one step back
249 });
250251 app.listen(3000); 252253### Middleware254255Middleware via [Connect](http://github.com/senchalabs/connect) can be256passed to _express.createServer()_ as you would with a regular Connect server. For example:257258 var express = require('express');259260 var app = express.createServer(261 express.logger()262 , express.bodyParser()263 );264

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

line 265why, one step back
265Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manner.

added quick start to guideTj Holowaychukbefore adoption723774a

lines 266–381why, one step back
266
267 app.use(express.logger({ format: ':method :url' }));268269Typically with connect middleware you would _require('connect')_ like so:270271 var connect = require('connect');272 app.use(connect.logger());273 app.use(connect.bodyParser());274275This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:276277 app.use(express.logger());278 app.use(express.bodyParser());279280Middleware 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()_.281282Many 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 below283284 app.use(express.logger(...));285 app.use(express.bodyParser(...));286 app.use(express.cookieParser(...));287 app.use(express.session(...));288 app.use(app.router);289 app.use(express.static(...));290 app.use(express.errorHandler(...));291292First 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.293294 var downloads = {};295296 app.use(app.router);297 app.use(express.static(__dirname + '/public'));298299 app.get('/*', function(req, res, next){300 var file = req.params[0];301 downloads[file] = downloads[file] || 0;302 downloads[file]++;303 next();304 });305306307### Route Middleware308309Routes 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.310311Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 312313 app.get('/user/:id', function(req, res, next){314 loadUser(req.params.id, function(err, user){315 if (err) return next(err);316 res.send('Viewing user ' + user.name);317 });318 });319320To 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. 321322 function loadUser(req, res, next) {323 // You would fetch your user from the db324 var user = users[req.params.id];325 if (user) {326 req.user = user;327 next();328 } else {329 next(new Error('Failed to load user ' + req.params.id));330 }331 }332 333 app.get('/user/:id', loadUser, function(req, res){334 res.send('Viewing user ' + req.user.name);335 });336337Multiple 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.338339 function andRestrictToSelf(req, res, next) {340 req.authenticatedUser.id == req.user.id341 ? next()342 : next(new Error('Unauthorized'));343 }344 345 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){346 res.send('Editing user ' + req.user.name);347 });348349Keeping 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.350351 function andRestrictTo(role) {352 return function(req, res, next) {353 req.authenticatedUser.role == role354 ? next()355 : next(new Error('Unauthorized'));356 }357 }358 359 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){360 res.send('Deleted user ' + req.user.name);361 });362363Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.364365 var a = [middleware1, middleware2]366 , b = [middleware3, middleware4]367 , all = [a, b];368 369 app.get('/foo', a, function(){});370 app.get('/bar', a, function(){});371 372 app.get('/', a, middleware3, middleware4, function(){});373 app.get('/', a, b, function(){});374 app.get('/', all, function(){});375376For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.377378There 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.379380### HTTP Methods381

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

line 382why, one step back
382We have seen _app.get()_ a few times, however Express also exposes other familiar HTTP verbs in the same manner, such as _app.post()_, _app.del()_, etc.

added quick start to guideTj Holowaychukbefore adoption723774a

lines 383–423why, one step back
383
384 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.385 386 <form method="post" action="/">387 <input type="text" name="user[name]" />388 <input type="text" name="user[email]" />389 <input type="submit" value="Submit" />390 </form>391392By 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:393394 app.use(express.bodyParser());395396Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.397398 app.post('/', function(req, res){399 console.log(req.body.user);400 res.redirect('back');401 });402403When 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.404405 app.use(express.bodyParser());406 app.use(express.methodOverride());407408The 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:409410 <form method="post" action="/">411 <input type="hidden" name="_method" value="put" />412 <input type="text" name="user[name]" />413 <input type="text" name="user[email]" />414 <input type="submit" value="Submit" /> 415 </form>416417 app.put('/', function(){418 console.log(req.body.user);419 res.redirect('back');420 });421422### Error Handling423

removed old error handling docsTj Holowaychukbefore adoptioned19885

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

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 432why, one step back
432 res.send(500, 'Server error');

added quick start to guideTj Holowaychukbefore adoption723774a

lines 433–495why, one step back
433 });
434435### Route Param Pre-conditions436437Route 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:438439 app.get('/user/:userId', function(req, res, next){440 User.get(req.params.userId, function(err, user){441 if (err) return next(err);442 res.send('user ' + user.name);443 });444 }); 445446With 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.447448 app.param('userId', function(req, res, next, id){449 User.get(id, function(err, user){450 if (err) return next(err);451 if (!user) return next(new Error('failed to find user'));452 req.user = user;453 next();454 });455 });456457Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:458459 app.get('/user/:userId', function(req, res){460 res.send('user ' + req.user.name);461 });462463### View Rendering464465View filenames take the form "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name466of the module that will be required. For example the view _layout.ejs_ will467tell 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 behaviour468_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.469470Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,471and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 472the _body_ local variable in _layout.jade_.473474 app.get('/', function(req, res){475 res.render('index.jade', { title: 'My Site' });476 });477478The new _view engine_ setting allows us to specify our default template engine,479so for example when using jade we could set:480481 app.set('view engine', 'jade');482483Allowing us to render with:484485 res.render('index');486487vs:488489 res.render('index.jade');490491When _view engine_ is set, extensions are entirely optional, however we can still492mix and match template engines:493494 res.render('another-page.ejs');495

Removed "view options" setting. Closes #748Tj Holowaychukbefore adoption3ec2739

line 496why, one step back
496 To apply application-level locals, or view engine options may be set using _app.local()_ or _app.locals()_, for example if we don't want layouts for most of our templates we may do:

added quick start to guideTj Holowaychukbefore adoption723774a

line 497why, one step back
497

Removed "view options" setting. Closes #748Tj Holowaychukbefore adoption3ec2739

line 498why, one step back
498 app.local('layout', false);

added quick start to guideTj Holowaychukbefore adoption723774a

line 499why, one step back
499

Removed "view options" setting. Closes #748Tj Holowaychukbefore adoption3ec2739

line 500why, one step back
500Which can then be overridden within the _res.render()_ call if desired, and is otherwise functionally equivalent to passing directly to `res.render()`:

added quick start to guideTj Holowaychukbefore adoption723774a

lines 501–567why, one step back
501
502 res.render('myview.ejs', { layout: true });503504When 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:505506 res.render('page', { layout: 'mylayout' });507508Otherwise we must specify the extension:509510 res.render('page', { layout: 'mylayout.jade' });511512These paths may also be absolute:513514 res.render('page', { layout: __dirname + '/../../mylayout.jade' });515516### View Partials517518The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating519in a view to display comments, we could use partial collection:520521 partial('comment', { collection: comments });522523If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:524525 partial('comment', comments);526527When using the partial collection support a few "magic" locals are provided528for free:529530 * _firstInCollection_ true if this is the first object531 * _indexInCollection_ index of the object in the collection532 * _lastInCollection_ true if this is the last object533 * _collectionLength_ length of the collection534535Local 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.536537For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).538539__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.540541### View Lookup542543View 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_.544545The 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_.546547When 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')_.548549### Template Engines550551Below are a few template engines commonly used with Express:552553 * [Haml](http://github.com/visionmedia/haml.js) haml implementation554 * [Jade](http://jade-lang.com) haml.js successor555 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript556 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating557 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node558559### Session Support560561Sessions 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_.562563 app.use(express.cookieParser());564 app.use(express.session({ secret: "keyboard cat" }));565566By 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:567

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 569–573why, one step back
569 app.use(express.cookieParser());
570 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));571572Now 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:573

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 575–591why, one step back
575 app.use(express.bodyParser());
576 app.use(express.cookieParser());577 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));578579 app.post('/add-to-cart', function(req, res){580 // Perhaps we posted several items with a form581 // (use the bodyParser() middleware for this)582 var items = req.body.items;583 req.session.items = items;584 res.redirect('back');585 });586587 app.get('/add-to-cart', function(req, res){588 // When redirected back to GET /add-to-cart589 // we could check req.session.items && req.session.items.length590 // to print out a message591 if (req.session.items && req.session.items.length) {

docsTj Holowaychukbefore adoption6f85c14

line 592why, one step back
592 req.notify('info', 'You have %s items in your cart', req.session.items.length);

added quick start to guideTj Holowaychukbefore adoption723774a

lines 593–705why, one step back
593 }
594 res.render('shopping-cart');595 });596597The _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.598599### Migration Guide600601 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.602603### req.header(key[, defaultValue])604605Get the case-insensitive request header _key_, with optional _defaultValue_:606607 req.header('Host');608 req.header('host');609 req.header('Accept', '*/*');610611The _Referrer_ and _Referer_ header fields are special-cased, either will work:612613 // sent Referrer: http://google.com614615 req.header('Referer');616 // => "http://google.com"617618 req.header('Referrer');619 // => "http://google.com"620621### req.accepts(type)622623Check if the _Accept_ header is present, and includes the given _type_.624625When the _Accept_ header is not present _true_ is returned. Otherwise626the given _type_ is matched by an exact match, and then subtypes. You627may pass the subtype such as "html" which is then converted internally628to "text/html" using the mime lookup table.629630 // Accept: text/html631 req.accepts('html');632 // => true633634 // Accept: text/*; application/json635 req.accepts('html');636 req.accepts('text/html');637 req.accepts('text/plain');638 req.accepts('application/json');639 // => true640641 req.accepts('image/png');642 req.accepts('png');643 // => false644645### req.is(type)646647Check if the incoming request contains the _Content-Type_648header field, and it contains the give mime _type_.649 650 // With Content-Type: text/html; charset=utf-8651 req.is('html');652 req.is('text/html');653 // => true654 655 // When Content-Type is application/json656 req.is('json');657 req.is('application/json');658 // => true659 660 req.is('html');661 // => false662 663Ad-hoc callbacks can also be registered with Express, to perform664assertions again the request, for example if we need an expressive665way to check if our incoming request is an image, we can register _"an image"_666callback:667 668 app.is('an image', function(req){669 return 0 == req.headers['content-type'].indexOf('image');670 });671 672Now within our route callbacks, we can use to to assert content types673such as _"image/jpeg"_, _"image/png"_, etc.674 675 app.post('/image/upload', function(req, res, next){676 if (req.is('an image')) {677 // do something678 } else {679 next();680 }681 });682683Keep in mind this method is _not_ limited to checking _Content-Type_, you684can perform any request assertion you wish.685686Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:687688 req.is('image/*');689690We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.691692 req.is('*/json');693694### req.param(name[, default])695696Return the value of param _name_ when present or _default_.697698 - Checks route params (_req.params_), ex: /user/:id699 - Checks query string params (_req.query_), ex: ?id=12700 - Checks urlencoded body params (_req.body_), ex: id=12701702To utilize urlencoded request bodies, _req.body_703should be an object. This can be done by using704the _express.bodyParser middleware.705

docs for req.get()Tj Holowaychukbefore adoption6bb100d

lines 706–716why, one step back
706### req.get(field, param)
707708 Get _field_'s _param_ value, defaulting to '' when the _param_709 or _field_ is not present.710711 req.get('content-disposition', 'filename');712 // => "something.png"713714 req.get('Content-Type', 'boundary');715 // => "--foo-bar-baz"716

docsTj Holowaychukbefore adoption6f85c14

line 717why, one step back
717### req.notify(type[, msg])

added quick start to guideTj Holowaychukbefore adoption723774a

lines 718–720why, one step back
718
719Queue flash _msg_ of the given _type_.720

docsTj Holowaychukbefore adoption6f85c14

lines 721–723why, one step back
721 req.notify('info', 'email sent');
722 req.notify('error', 'email delivery failed');723 req.notify('info', 'email re-sent');

added quick start to guideTj Holowaychukbefore adoption723774a

lines 724–725why, one step back
724 // => 2
725

docsTj Holowaychukbefore adoption6f85c14

line 726why, one step back
726 req.notify('info');

added quick start to guideTj Holowaychukbefore adoption723774a

lines 727–728why, one step back
727 // => ['email sent', 'email re-sent']
728

docsTj Holowaychukbefore adoption6f85c14

line 729why, one step back
729 req.notify('info');

added quick start to guideTj Holowaychukbefore adoption723774a

lines 730–731why, one step back
730 // => []
731

docsTj Holowaychukbefore adoption6f85c14

line 732why, one step back
732 req.notify();

added quick start to guideTj Holowaychukbefore adoption723774a

lines 733–734why, one step back
733 // => { error: ['email delivery failed'], info: [] }
734

docsTj Holowaychukbefore adoption6f85c14

line 735why, one step back
735Flash notification message may also utilize formatters, by default only the %s string and %d integer formatters is available:

added quick start to guideTj Holowaychukbefore adoption723774a

line 736why, one step back
736

misc refactoringTj Holowaychukbefore adoption77d8823

line 737why, one step back
737 req.notify('info', 'email delivery to <em>%s</em> from <em>%s</em> failed.', toUser, fromUser);

docsTj Holowaychukbefore adoption6f85c14

line 738why, one step back
738

misc refactoringTj Holowaychukbefore adoption77d8823

line 739why, one step back
739Argument HTML is escaped, to prevent XSS, however HTML notification format is valid.

added quick start to guideTj Holowaychukbefore adoption723774a

lines 740–801why, one step back
740
741### req.isXMLHttpRequest742743Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header744to see if it was issued by an _XMLHttpRequest_:745746 req.xhr747 req.isXMLHttpRequest748749### res.header(key[, val])750751Get or set the response header _key_.752753 res.header('Content-Length');754 // => undefined755756 res.header('Content-Length', 123);757 // => 123758 759 res.header('Content-Length');760 // => 123761762### res.charset763764Sets 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:765766 res.charset = 'ISO-8859-1';767 res.render('users');768769or before responding with `res.send()`:770771 res.charset = 'ISO-8859-1';772 res.send(str);773774or with node's `res.end()`:775776 res.charset = 'ISO-8859-1';777 res.header('Content-Type', 'text/plain');778 res.end(str);779780### res.contentType(type)781782Sets the _Content-Type_ response header to the given _type_.783784 var filename = 'path/to/image.png';785 res.contentType(filename);786 // Content-Type is now "image/png"787788A literal _Content-Type_ works as well:789790 res.contentType('application/json');791792Or simply the extension without leading `.`:793794 res.contentType('json');795796### res.attachment([filename])797798Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.799800 res.attachment('path/to/my/image.png');801

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

lines 802–816why, one step back
802### res.status(code)
803804 Sets the `res.statusCode` property to `code` and returns for chaining:805806 res.status(500).send('Something bad happened');807808 is equivalent to:809 810 res.statusCode = 500;811 res.send('Something bad happened');812813 and:814815 res.send(500, 'Something bad happened');816

added quick start to guideTj Holowaychukbefore adoption723774a

lines 817–865why, one step back
817### res.sendfile(path[, options[, callback]])
818819Used by `res.download()` to transfer an arbitrary file. 820821 res.sendfile('path/to/my.file');822823This method accepts an optional callback which is called when824an 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.825826 res.sendfile(path, function(err){827 if (err) {828 next(err);829 } else {830 console.log('transferred %s', path);831 }832 });833834Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:835836 res.sendfile(path, { bufferSize: 1024 }, function(err){837 // handle838 });839840### res.download(file[, filename[, callback[, callback2]]])841842Transfer the given _file_ as an attachment with optional alternative _filename_.843844 res.download('path/to/image.png');845 res.download('path/to/image.png', 'foo.png');846847This is equivalent to:848849 res.attachment(file);850 res.sendfile(file);851852An 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.853854 res.download(path, 'expenses.doc', function(err){855 // handle856 });857858An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.859860 res.download(path, function(err){861 // error or finished862 }, function(err){863 // connection related error864 });865

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 866why, one step back
866### res.send(body|status[, body])

added quick start to guideTj Holowaychukbefore adoption723774a

lines 867–872why, one step back
867
868The _res.send()_ method is a high level response utility allowing you to pass869objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:870871 res.send(new Buffer('wahoo'));872 res.send({ some: 'json' });

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 873why, one step back
873 res.send(201, { message: 'User created' });

added quick start to guideTj Holowaychukbefore adoption723774a

line 874why, one step back
874 res.send('<p>some html</p>');

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

lines 875–877why, one step back
875 res.send(404, 'Sorry, cant find that');
876 res.send(404); // "Not Found"877 res.send(500); // "Internal Server Error"

added quick start to guideTj Holowaychukbefore adoption723774a

line 878why, one step back
878

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 879why, one step back
879The _Content-Type_ response header is defaulted appropriately unless previously defined via `res.header()` / `res.contentType()` etc.

added quick start to guideTj Holowaychukbefore adoption723774a

lines 880–882why, one step back
880
881Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.882

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 883why, one step back
883### res.json(obj|status[, obj])

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

line 884why, one step back
884

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 885why, one step back
885 Send an explicit JSON response. This method is ideal for JSON-only APIs, while it is much like _res.send(obj)_, send is not ideal for cases when you want to send for example a single string as JSON, since the default for _res.send(string)_ is text/html.

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

lines 886–888why, one step back
886
887 res.json(null);888 res.json({ user: 'tj' });

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

lines 889–890why, one step back
889 res.json(500, 'oh noes!');
890 res.json(404, 'I dont have that');

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

line 891why, one step back
891

added quick start to guideTj Holowaychukbefore adoption723774a

lines 892–907why, one step back
892### res.redirect(url[, status])
893894Redirect to the given _url_ with a default response _status_ of 302.895896 res.redirect('/', 301);897 res.redirect('/account');898 res.redirect('http://google.com');899 res.redirect('home');900 res.redirect('back');901902Express supports "redirect mapping", which by default provides _home_, and _back_.903The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes904the "home" setting and defaults to "/".905906### res.cookie(name, val[, options])907

docsTj Holowaychukbefore adoption6815feb

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 910–927why, one step back
910
911 // "Remember me" for 15 minutes 912 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });913914The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:915916 res.cookie('rememberme', 'yes', { maxAge: 900000 });917918To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:919920 app.use(express.cookieParser());921 922 app.get('/', function(req, res){923 // use req.cookies.rememberme924 });925926### res.clearCookie(name[, options])927

docsTj Holowaychukbefore adoption6815feb

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 930–943why, one step back
930
931 res.clearCookie('rememberme');932933### res.render(view[, options[, fn]])934935Render _view_ with the given _options_ and optional callback _fn_.936When a callback function is given a response will _not_ be made937automatically, however otherwise a response of _200_ and _text/html_ is given.938939The _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:940941 var user = { name: 'tj' };942 res.render('index', { layout: false, user: user });943

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 953–1165why, one step back
953### res.partial(view[, options])
954955Render _view_ partial with the given _options_. This method is always available956to the view as a local variable.957958- _object_ the object named by _as_ or derived from the view name959- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.960 * as: 'something' will add the _something_ local variable961 * as: this will use the collection value as the template context962 * as: global will merge the collection value's properties with _locals_963964- _collection_ Array of objects, the name is derived from the view name itself. 965 For example _video.html_ will have a object _video_ available to it.966967The following are equivalent, and the name of collection value when passed968to the partial will be _movie_ as derived from the name.969970 partial('theatre/movie.jade', { collection: movies });971 partial('theatre/movie.jade', movies);972 partial('movie.jade', { collection: movies });973 partial('movie.jade', movies);974 partial('movie', movies);975 // In view: movie.director976977To change the local from _movie_ to _video_ we can use the "as" option:978979 partial('movie', { collection: movies, as: 'video' });980 // In view: video.director981982Also we can make our movie the value of _this_ within our view so that instead983of _movie.director_ we could use _this.director_.984985 partial('movie', { collection: movies, as: this });986 // In view: this.director987988Another alternative is to "expand" the properties of the collection item into989pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:990991 partial('movie', { collection: movies, as: global });992 // In view: director993994This same logic applies to a single partial object usage:995996 partial('movie', { object: movie, as: this });997 // In view: this.director998999 partial('movie', { object: movie, as: global });1000 // In view: director10011002 partial('movie', { object: movie, as: 'video' });1003 // In view: video.director10041005 partial('movie', { object: movie });1006 // In view: movie.director10071008When 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:10091010 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1011 partial('movie', movie)1012 // => In view: movie.director10131014The 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:10151016 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1017 partial('movie', movie)10181019For 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:10201021 partial('movie', { locals: { movie: movie }})1022 partial('movie', { movie: movie })1023 partial('movie', { object: movie })10241025This 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:10261027 app.get('/users', function(req, res){1028 if (req.xhr) {1029 // respond with the each user in the collection1030 // passed to the "user" view1031 res.partial('user', users);1032 } else {1033 // respond with layout, and users page1034 // which internally does partial('user', users)1035 // along with other UI1036 res.render('users', { users: users });1037 }1038 });10391040### res.local(name[, val])10411042Get 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()`.10431044 app.all('/movie/:id', function(req, res, next){1045 Movie.get(req.params.id, function(err, movie){1046 // Assigns res.locals.movie = movie1047 res.local('movie', movie);1048 });1049 });1050 1051 app.get('/movie/:id', function(req, res){1052 // movie is already a local, however we1053 // can pass more if we wish1054 res.render('movie', { displayReviews: true });1055 });10561057### res.locals(obj)10581059 Assign several locals with the given _obj_. The following are equivalent:1060 1061 res.local('foo', bar);1062 res.local('bar', baz);10631064 res.locals({ foo: bar, bar, baz });10651066### app.set(name[, val])10671068Apply an application level setting _name_ to _val_, or1069get the value of _name_ when _val_ is not present:10701071 app.set('views', __dirname + '/views');1072 app.set('views');1073 // => ...path...10741075Alternatively you may simply access the settings via _app.settings_:10761077 app.settings.views1078 // => ...path...10791080### app.enable(name)10811082Enable the given setting _name_:10831084 app.enable('some arbitrary setting');1085 app.set('some arbitrary setting');1086 // => true10871088 app.enabled('some arbitrary setting');1089 // => true10901091### app.enabled(name)10921093Check if setting _name_ is enabled:10941095 app.enabled('view cache');1096 // => false10971098 app.enable('view cache');1099 app.enabled('view cache');1100 // => true11011102### app.disable(name)11031104Disable the given setting _name_:11051106 app.disable('some setting');1107 app.set('some setting');1108 // => false1109 1110 app.disabled('some setting');1111 // => false11121113### app.disabled(name)11141115Check if setting _name_ is disabled:11161117 app.enable('view cache');11181119 app.disabled('view cache');1120 // => false11211122 app.disable('view cache');1123 app.disabled('view cache');1124 // => true11251126### app.configure(env|function[, function])11271128Define a callback function for the given _env_ (or all environments) with callback _function_:11291130 app.configure(function(){1131 // executed for each env1132 });11331134 app.configure('development', function(){1135 // executed for 'development' only1136 });11371138### app.redirect(name, val)11391140For use with _res.redirect()_ we can map redirects at the application level as shown below:11411142 app.redirect('google', 'http://google.com');11431144Now in a route we may call:11451146 res.redirect('google');11471148We may also map dynamic redirects:11491150 app.redirect('comments', function(req, res){1151 return '/post/' + req.params.id + '/comments';1152 });11531154So now we may do the following, and the redirect will dynamically adjust to1155the context of the request. If we called this route with _GET /post/12_ our1156redirect _Location_ would be _/post/12/comments_.11571158 app.get('/post/:id', function(req, res){1159 res.redirect('comments');1160 });11611162When 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_:11631164 res.redirect('/posts');1165

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

line 1167why, one step back
1167

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

line 1169why, one step back
1169

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 1171–1185why, one step back
1171 name: function(first, last){ return first + ', ' + last }
1172 , firstName: 'tj'1173 , lastName: 'holowaychuk'1174 });11751176Our view could now utilize the _firstName_ and _lastName_ variables,1177as well as the _name()_ function exposed.11781179 <%= name(firstName, lastName) %>11801181Express also provides a few locals by default:11821183 - `settings` the app's settings object1184 - `layout(path)` specify the layout from within a view1185

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

line 1187why, one step back
1187

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

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

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

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

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 1194–1366why, one step back
1194 session: function(req, res){
1195 return req.session;1196 }1197 });11981199All views would now have _session_ available so that session data can be accessed via _session.name_ etc:12001201 <%= session.name %>12021203### app.lookup12041205 The _app.lookup_ http methods returns an array of callback functions1206 associated with the given _path_.12071208 Suppose we define the following routes:1209 1210 app.get('/user/:id', function(){});1211 app.put('/user/:id', function(){});1212 app.get('/user/:id/:op?', function(){});12131214 We can utilize this lookup functionality to check which routes1215 have been defined, which can be extremely useful for higher level1216 frameworks built on Express.12171218 app.lookup.get('/user/:id');1219 // => [Function]12201221 app.lookup.get('/user/:id/:op?');1222 // => [Function]12231224 app.lookup.put('/user/:id');1225 // => [Function]12261227 app.lookup.all('/user/:id');1228 // => [Function, Function]12291230 app.lookup.all('/hey');1231 // => []12321233 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1234 without a callback, as a shortcut, for example the following are1235 equivalent:1236 1237 app.lookup.get('/user');1238 app.get('/user');12391240 Each function returned has the following properties:1241 1242 var fn = app.get('/user/:id/:op?')[0];12431244 fn.regexp1245 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12461247 fn.keys1248 // => ['id', 'op']12491250 fn.path1251 // => '/user/:id/:op?'12521253 fn.method1254 // => 'GET'12551256### app.match12571258 The _app.match_ http methods return an array of callback functions1259 which match the given _url_, which may include a query string etc. This1260 is useful when you want reflect on which routes have the opportunity to1261 respond.12621263 Suppose we define the following routes:12641265 app.get('/user/:id', function(){});1266 app.put('/user/:id', function(){});1267 app.get('/user/:id/:op?', function(){});12681269 Our match against __GET__ will return two functions, since the _:op_1270 in our second route is optional.12711272 app.match.get('/user/1');1273 // => [Function, Function]12741275 This second call returns only the callback for _/user/:id/:op?_.12761277 app.match.get('/user/23/edit');1278 // => [Function]12791280 We can also use _all()_ to disregard the http method:12811282 app.match.all('/user/20');1283 // => [Function, Function, Function]12841285 Each function matched has the following properties:1286 1287 var fn = app.match.get('/user/23/edit')[0];12881289 fn.keys1290 // => ['id', 'op']12911292 fn.params1293 // => { id: '23', op: 'edit' }12941295 fn.method1296 // => 'GET'12971298### app.mounted(fn)12991300Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.13011302 var app = express.createServer(),1303 blog = express.createServer();1304 1305 blog.mounted(function(parent){1306 // parent is app1307 // "this" is blog1308 });1309 1310 app.use(blog);13111312### app.register(ext, exports)13131314Register the given template engine _exports_1315as _ext_. For example we may wish to map ".html"1316files to jade:13171318 app.register('.html', require('jade'));13191320This is also useful for libraries that may not1321match extensions correctly. For example my haml.js1322library is installed from npm as "hamljs" so instead1323of layout.hamljs, we can register the engine as ".haml":13241325 app.register('.haml', require('haml-js'));13261327For engines that do not comply with the Express1328specification, we can also wrap their api this way. Below1329we map _.md_ to render markdown files, rendering the html once1330since it will not change on subsequent calls, and support local substitution1331in the form of "{name}".13321333 app.register('.md', {1334 compile: function(str, options){1335 var html = md.toHTML(str);1336 return function(locals){1337 return html.replace(/\{([^}]+)\}/g, function(_, name){1338 return locals[name];1339 });1340 };1341 }1342 });13431344### app.listen([port[, host]])13451346Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1347connections will be accepted via _INADDR_ANY_.13481349 app.listen();1350 app.listen(3000);1351 app.listen(3000, 'n.n.n.n');13521353The _port_ argument may also be a string representing the path to a unix domain socket:13541355 app.listen('/tmp/express.sock');13561357Then try it out:13581359 $ telnet /tmp/express.sock1360 GET / HTTP/1.113611362 HTTP/1.1 200 OK1363 Content-Type: text/plain1364 Content-Length: 111365 1366 Hello World