guide.md
This file
Path
docs/guide.md
846 lines · 27.1 KiB · Markdown
Last changed by
Added route-middleware exampleTj Holowaychukbefore adoption4983e96
History of this fileTake it
The walk stopped after 200 commits: lines older than 0283a73 point at it.
Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 1–3why, one step back12### Installation3No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9
line 4why, one step back4curl:Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 5–40why, one step back56 $ curl -# http://expressjs.com/install.sh | sh78npm:910 $ npm install express1112git clone, first update the submodules:1314 $ git submodule update --init15 $ make install16 $ make install-support1718### Creating An Application1920The _express.Server_ now inherits from _http.Server_, however21follows the same idiom by providing _express.createServer()_ as shown below. This means22that you can utilize Express server's transparently with other libraries.2324 var app = require('express').createServer();25 26 app.get('/', function(req, res){27 res.send('hello world');28 });29 30 app.listen(3000);3132### Configuration3334Express supports arbitrary environments, such as _production_ and _development_. Developers35can use the _configure()_ method to setup needs required by the current environment. When36_configure()_ is called without an environment name it will be run in _every_ environment 37prior to the environment specific callback.3839In the example below we only _dumpExceptions_, and respond with exception stack traces40in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
lines 41–42why, one step back41Note the use of _app.router_, which can (optionally) be used to mount the application routes,42otherwise the first call to _app.{get,put,del,post}()_ will mount the routes.Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 43–44why, one step back4344 app.configure(function(){Updated docsTj Holowaychukbefore adoption344218f
lines 45–46why, one step back45 app.use(express.methodOverride());46 app.use(express.bodyDecoder());Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
line 47why, one step back47 app.use(app.router);Updated docsTj Holowaychukbefore adoption344218f
line 48why, one step back48 app.use(express.staticProvider(__dirname + '/public'));Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 49–51why, one step back49 });50 51 app.configure('development', function(){Updated docsTj Holowaychukbefore adoption344218f
line 52why, one step back52 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 53–55why, one step back53 });54 55 app.configure('production', function(){Updated docsTj Holowaychukbefore adoption344218f
line 56why, one step back56 app.use(express.errorHandler());Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 57–72why, one step back57 });5859For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:6061 app.configure(function(){62 app.set('views', __dirname + '/views');63 app.set('views');64 // => "... views directory ..."65 66 app.enable('some feature');67 // same as app.set('some feature', true);68 69 app.disable('some feature');70 // same as app.set('some feature', false);71 });72Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab
line 73why, one step back73To alter the environment we can set the _NODE_ENV_ environment variable, for example:Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
line 74why, one step back74Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab
line 75why, one step back75 $ NODE_ENV=production node app.jsRemoved instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 76–80why, one step back7677### Settings7879Express supports the following settings out of the box:80Updated docsTj Holowaychukbefore adoption4d32762
line 81why, one step back81 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_New "home" docsTj Holowaychukbefore adoption1e7a12f
line 82why, one step back82 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 83–84why, one step back83 * _views_ Root views directory defaulting to **CWD/views**84 * _view engine_ Default view engine name for views rendered without extensionsMerge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 85why, one step back85 * _view options_ An object specifying global view optionsMerge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 86–87why, one step back86 * _partials_ Root view partials directory defaulting to _views_/partials.87 * _stream threshold_ Bytesize indicating when a file should be streamed for _res.sendfile()_ using _fs.ReadStream()_ and _sys.pump()_.Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 88–92why, one step back8889### Routing9091Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.92For example we may want to render a user's account for the path _/user/12_, thisUpdated docsTj Holowaychukbefore adoptiond691ecb
lines 93–94why, one step back93can be done by defining the route below. The values associated to the named placeholders 94are available as `req.params`.Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
line 95why, one step back95Updated docsTj Holowaychukbefore adoptiond691ecb
lines 96–97why, one step back96 app.get('/user/:id', function(req, res){97 res.send('user ' + req.params.id);Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 98–104why, one step back98 });99100A route is simple a string which is compiled to a _RegExp_ internally. For example101when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:102103 \/user\/([^\/]+)\/?104Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
line 105why, one step back105Regular expression literals may also be passed for complex uses. Since captureUpdated docsTj Holowaychukbefore adoptiond691ecb
line 106why, one step back106groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
line 107why, one step back107Updated docsTj Holowaychukbefore adoptiond691ecb
lines 108–109why, one step back108 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){109 res.send(req.params);Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
lines 110–121why, one step back110 });111112Curl requests against the previously defined route:113114 $ curl http://dev:3000/user115 [null,null]116 $ curl http://dev:3000/users117 [null,null]118 $ curl http://dev:3000/users/1119 ["1",null]120 $ curl http://dev:3000/users/1..15121 ["1","15"]Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 122–155why, one step back122123Below are some route examples, and the associated paths that they124may consume:125126 "/user/:id"127 /user/12128129 "/users/:id?"130 /users/5131 /users132133 "/files/*"134 /files/jquery.js135 /files/javascripts/jquery.js136137 "/file/*.*"138 /files/jquery.js139 /files/javascripts/jquery.js140 141 "/user/:id/:operation?"142 /user/1143 /user/1/edit144 145 "/products.:format"146 /products.json147 /products.xml148149 "/products.:format?"150 /products.json151 /products.xml152 /products153154### Passing Route Control155Updated docsTj Holowaychukbefore adoptiond691ecb
lines 156–157why, one step back156We may pass control to the next _matching_ route, by calling the _third_ argument,157the _next()_ function. When a match cannot be made, control is passed back to Connect,Added route-middleware exampleTj Holowaychukbefore adoption4983e96
line 158why, one step back158and middleware continue to be invoked. The same is true for several routes which have the same path defined, they will simply be executed in order until one does _not_ call _next()_.Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
line 159why, one step back159Fixed doc typoTj Holowaychukbefore adoption47ff7d9
line 160why, one step back160 app.get('/users/:id?', function(req, res, next){Updated docsTj Holowaychukbefore adoptiond691ecb
lines 161–162why, one step back161 var id = req.params.id;162 if (id) {Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 163–168why, one step back163 // do something164 } else {165 next();166 }167 });168 Updated docsTj Holowaychukbefore adoptiond691ecb
line 169why, one step back169 app.get('/users', function(req, res){Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 170–171why, one step back170 // do something else171 });Added route-middleware exampleTj Holowaychukbefore adoption4983e96
lines 172–175why, one step back172173### Route Middleware174175Routes 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.Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
line 176why, one step back176HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 177–218why, one step back177### HTTP Methods178179We 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.180181 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.182 183 <form method="post" action="/">184 <input type="text" name="user[name]" />185 <input type="text" name="user[email]" />186 <input type="submit" value="Submit" />187 </form>188189By default Express does not know what to do with this request body, so we should add the _bodyDecoder_ middleware, which will parse _application/x-www-form-urlencoded_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:190191 app.use(express.bodyDecoder());192193Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.194195 app.post('/', function(req, res){196 console.log(req.body.user);197 res.redirect('back');198 });199200When 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 _bodyDecoder_ so that it can utilize it's _req.body_ containing the form values.201202 app.use(express.bodyDecoder());203 app.use(express.methodOverride());204205The 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:206207 <form method="post" action="/">208 <input type="hidden" name="_method" value="put" />209 <input type="text" name="user[name]" />210 <input type="text" name="user[email]" />211 <input type="submit" value="Submit" /> 212 </form>213214 app.put('/', function(){215 console.log(req.body.user);216 res.redirect('back');217 });218Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 219–220why, one step back219### Middleware220Added session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe
line 221why, one step back221Middleware via [Connect](http://github.com/senchalabs/connect) can beRemoved instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 222–223why, one step back222passed to _express.createServer()_ as you would with a regular Connect server. For example:223Added session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe
line 224why, one step back224 var express = require('express');Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 225–226why, one step back225226 var app = express.createServer(Added session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe
lines 227–229why, one step back227 express.logger(),228 express.bodyDecoder()229 );Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 230–232why, one step back230231Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:232Updated docsTj Holowaychukbefore adoption344218f
line 233why, one step back233 app.use(express.logger({ format: ':method :uri' }));Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
line 234why, one step back234Updated docsTj Holowaychukbefore adoption344218f
lines 235–243why, one step back235Typically with connect middleware you would _require('connect')_ like so:236237 var connect = require('connect');238 app.use(connect.logger());239240This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:241242 app.use(express.logger());243Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 244–269why, one step back244### Error Handling245246Express provides the _app.error()_ method which receives exceptions thrown within a route,247or passed to _next(err)_. Below is an example which serves different pages based on our248ad-hoc _NotFound_ exception:249250 function NotFound(msg){251 this.name = 'NotFound';252 Error.call(this, msg);253 Error.captureStackTrace(this, arguments.callee);254 }255256 sys.inherits(NotFound, Error);257258 app.get('/404', function(req, res){259 throw new NotFound;260 });261262 app.get('/500', function(req, res){263 throw new Error('keyboard cat!');264 });265266We can call _app.error()_ several times as shown below.267Here we check for an instanceof _NotFound_ and show the268404 page, or we pass on to the next error handler.269Merge branch 'fix-error'Tj Holowaychukbefore adoption498115d
lines 270–274why, one step back270Note that these handlers can be defined anywhere, as they271will be placed below the route handlers on _listen()_. This 272allows for definition within _configure()_ blocks so we can273handle exceptions in different ways based on the environment.274Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 275–297why, one step back275 app.error(function(err, req, res, next){276 if (err instanceof NotFound) {277 res.render('404.jade');278 } else {279 next(err);280 }281 });282283Here we assume all errors as 500 for the simplicity of284this demo, however you can choose whatever you like285286 app.error(function(err, req, res){287 res.render('500.jade', {288 locals: {289 error: err290 } 291 });292 });293294Our apps could also utilize the Connect _errorHandler_ middleware295to report on exceptions. For example if we wish to output exceptions 296in "development" mode to _stderr_ we can use:297Updated docsTj Holowaychukbefore adoption344218f
line 298why, one step back298 app.use(express.errorHandler({ dumpExceptions: true }));Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 299–302why, one step back299300Also during development we may want fancy html pages to show exceptions301that are passed or thrown, so we can set _showStack_ to true:302Updated docsTj Holowaychukbefore adoption344218f
line 303why, one step back303 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 304–311why, one step back304305The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_306is present, which is useful for developing apps that rely heavily on client-side JavaScript.307308### View Rendering309310View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name311of the module that will be required. For example the view _layout.ejs_ willAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 312–313why, one step back312tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 313_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 314–341why, one step back314315Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,316and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 317the _body_ local variable in _layout.haml_.318319 app.get('/', function(req, res){320 res.render('index.haml', {321 locals: { title: 'My Site' }322 });323 });324325The new _view engine_ setting allows us to specify our default template engine,326so for example when using [Jade](http://github.com/visionmedia/jade) we could set:327328 app.set('view engine', 'jade');329330Allowing us to render with:331332 res.render('index');333334vs:335336 res.render('index.jade');337338When _view engine_ is set, extensions are entirely optional, however we can still339mix and match template engines:340341 res.render('another-page.ejs');Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 342–352why, one step back342343Express 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:344345 app.set('view options', {346 layout: false347 });348349Which can then be overridden within the `res.render()` call if need be:350351 res.render('myview.ejs', { layout: true });352Docs for layout optionTj Holowaychukbefore adoption0a96621
lines 353–364why, one step back353When 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:354355 res.render('page', { layout: 'mylayout' });356357Otherwise we must specify the extension:358359 res.render('page', { layout: 'mylayout.jade' });360361These paths may also be absolute:362363 res.render('page', { layout: __dirname + '/../../mylayout.jade' });364Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 365–370why, one step back365A good example of this is specifying custom _ejs_ opening and closing tags:366367 app.set('view options', {368 open: '{{',369 close: '}}'370 });Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 371–394why, one step back371372### View Partials373374The Express view system has built-in support for partials and collections, which are375sort of "mini" views representing a document fragment. For example rather than iterating376in a view to display comments, we would use a partial with collection support:377378 partial('comment.haml', { collection: comments });379380To make things even less verbose we can assume the extension as _.haml_ when omitted,381however if we wished we could use an ejs partial, within a haml view for example.382383 partial('comment', { collection: comments });384385And once again even further, when rendering a collection we can simply pass386an array, if no other options are desired:387388 partial('comments', comments);389390When using the partial collection support a few "magic" variables are provided391for free:392393 * _firstInCollection_ True if this is the first object394 * _indexInCollection_ Index of the object in the collectionDoc typosTj Holowaychukbefore adoption02b4ec0
line 395why, one step back395 * _lastInCollection_ True if this is the last objectRemoved instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 396–400why, one step back396397### Template Engines398399Below are a few template engines commonly used with Express:400Doc typosTj Holowaychukbefore adoption02b4ec0
lines 401–402why, one step back401 * [Jade](http://jade-lang.com) haml.js successor402 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templatesRemoved instanceof Array checkTj Holowaychukbefore adoption0283a73
line 403why, one step back403 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScriptAdded session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe
lines 404–416why, one step back404405### Session Support406407Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieDecoder_ middleware place above it, which will parse and populate cookie data to _req.cookies_.408409 app.use(express.cookieDecoder());410 app.use(express.session());411412By 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:413414 var RedisStore = require('connect-redis');415 app.use(express.cookieDecoder());416 app.use(express.session({ store: new RedisStore }));Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
line 417why, one step back417More session docsTj Holowaychukbefore adoption4bc8a86
lines 418–444why, one step back418Now 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:419420 var RedisStore = require('connect-redis');421 app.use(express.cookieDecoder());422 app.use(express.session({ store: new RedisStore }));423 app.use(express.bodyDecoder());424425 app.post('/add-to-cart', function(req, res){426 // Perhaps we posted several items with a form427 // (use the bodyDecoder() middleware for this)428 var items = req.body.items;429 req.session.items = items;430 res.redirect('back');431 });432433 app.get('/add-to-cart', function(req, res){434 // When redirected back to GET /add-to-cart435 // we could check req.session.items && req.session.items.length436 // to print out a message437 if (req.session.items && req.session.items.length) {438 req.flash('info', 'You have %s items in your cart', req.session.items.length);439 }440 res.render('shopping-cart');441 });442443The _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/session.html) documentation.444Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 445–480why, one step back445### req.header(key[, defaultValue])446447Get the case-insensitive request header _key_, with optional _defaultValue_:448449 req.header('Host');450 req.header('host');451 req.header('Accept', '*/*');452453### req.accepts(type)454455Check if the _Accept_ header is present, and includes the given _type_.456457When the _Accept_ header is not present _true_ is returned. Otherwise458the given _type_ is matched by an exact match, and then subtypes. You459may pass the subtype such as "html" which is then converted internally460to "text/html" using the mime lookup table.461462 // Accept: text/html463 req.accepts('html');464 // => true465466 // Accept: text/*; application/json467 req.accepts('html');468 req.accepts('text/html');469 req.accepts('text/plain');470 req.accepts('application/json');471 // => true472473 req.accepts('image/png');474 req.accepts('png');475 // => false476477### req.param(name)478479Return the value of param _name_ when present.480Updated docsTj Holowaychukbefore adoptiond691ecb
lines 481–483why, one step back481 - Checks route placeholders (_req.params_), ex: /user/:id482 - Checks query string params (_req.query_), ex: ?id=12483 - Checks urlencoded body params (_req.body_), ex: id=12Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 484–486why, one step back484485To utilize urlencoded request bodies, _req.body_486should be an object. This can be done by usingUpdated docsTj Holowaychukbefore adoption344218f
line 487why, one step back487the _express.bodyDecoder_ middleware.Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 488–506why, one step back488489### req.flash(type[, msg])490491Queue flash _msg_ of the given _type_.492493 req.flash('info', 'email sent');494 req.flash('error', 'email delivery failed');495 req.flash('info', 'email re-sent');496 // => 2497498 req.flash('info');499 // => ['email sent', 'email re-sent']500501 req.flash('info');502 // => []503504 req.flash();505 // => { error: ['email delivery failed'], info: [] }506Added flash formatter docsTj Holowaychukbefore adoptionf16978d
lines 507–510why, one step back507Flash notification message may also utilize formatters, by default only the %s string formatter is available:508509 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);510Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 511–551why, one step back511### req.isXMLHttpRequest512513Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header514to see if it was issued by an _XMLHttpRequest_:515516 req.xhr517 req.isXMLHttpRequest518519### res.header(key[, val])520521Get or set the response header _key_.522523 res.header('Content-Length');524 // => undefined525526 res.header('Content-Length', 123);527 // => 123528529 res.header('Content-Length');530 // => 123531532### res.contentType(type)533534Sets the _Content-Type_ response header to the given _type_.535536 var filename = 'path/to/image.png';537 res.contentType(filename);538 // res.headers['Content-Type'] is now "image/png"539540### res.attachment([filename])541542Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.543544 res.attachment('path/to/my/image.png');545546### res.sendfile(path)547548Used by `res.download()` to transfer an arbitrary file. 549550 res.sendfile('path/to/my.file');551Merge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 552–562why, one step back552This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has __not__ been streamed, _next(err)_ will be called on an exception.553554 res.sendfile(path, function(err, path){555 if (err) {556 // handle the error557 } else {558 console.log('transferred %s', path);559 }560 });561562When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 563–581why, one step back563564### res.download(file[, filename])565566Transfer the given _file_ as an attachment with optional alternative _filename_.567568 res.download('path/to/image.png');569 res.download('path/to/image.png', 'foo.png');570571This is equivalent to:572573 res.attachment(file);574 res.sendfile(file);575576### res.send(body|status[, headers|status[, status]])577578The `res.send()` method is a high level response utility allowing you to pass579objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status580code based responses. The following are all valid uses:581Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
line 582why, one step back582 res.send(); // 204Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 583–607why, one step back583 res.send(new Buffer('wahoo'));584 res.send({ some: 'json' });585 res.send('<p>some html</p>');586 res.send('Sorry, cant find that', 404);587 res.send('text', { 'Content-Type': 'text/plain' }, 201);588 res.send(404);589590By default the _Content-Type_ response header is set, however if explicitly591assigned through `res.send()` or previously with `res.header()` or `res.contentType()`592it will not be set again.593594### res.redirect(url[, status])595596Redirect to the given _url_ with a default response _status_ of 302.597598 res.redirect('/', 301);599 res.redirect('/account');600 res.redirect('http://google.com');601 res.redirect('home');602 res.redirect('back');603604Express supports "redirect mapping", which by default provides _home_, and _back_.605The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes606the "home" setting and defaults to "/".607Cookie docsTj Holowaychukbefore adoptiona89767c
lines 608–628why, one step back608### res.cookie(name, val[, options])609610Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.611612 // "Remember me" for 15 minutes 613 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });614615To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:616617 app.use(express.cookieDecoder());618 619 app.get('/', function(req, res){620 // use req.cookies.rememberme621 });622623### res.clearCookie(name)624625Clear cookie _name_ by setting "expires" far in the past.626627 res.clearCookie('rememberme');628Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 629–637why, one step back629### res.render(view[, options[, fn]])630631Render _view_ with the given _options_ and optional callback _fn_.632When a callback function is given a response will _not_ be made633automatically, however otherwise a response of _200_ and _text/html_ is given.634635 Most engines accept one or more of the following options,636 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:637Updated docsTj Holowaychukbefore adoptionfd4c88d
line 638why, one step back638 - _scope_ Template evaluation context (value of _this_)Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 639–640why, one step back639 - _locals_ Object containing local variables640 - _debug_ Output debugging informationMerge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
lines 641–642why, one step back641 - _status_ Response status code, defaults to 200642 - _headers_ Response headers objectRemoved instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 643–686why, one step back643644### res.partial(view[, options])645646Render _view_ partial with the given _options_. This method is always available647to the view as a local variable.648649- _as_ Variable name for each _collection_ value, defaults to the view name.650 * as: 'something' will add the _something_ local variable651 * as: this will use the collection value as the template context652 * as: global will merge the collection value's properties with _locals_653654- _collection_ Array of objects, the name is derived from the view name itself. 655 For example _video.html_ will have a object _video_ available to it.656657The following are equivalent, and the name of collection value when passed658to the partial will be _movie_ as derived from the name.659660 partial('movie.jade', { collection: movies });661 partial('movie.jade', movies);662 partial('movie', movies);663 // In view: movie.director664665To change the local from _movie_ to _video_ we can use the "as" option:666667 partial('movie', { collection: movies, as: 'video' });668 // In view: video.director669670Also we can make our movie the value of _this_ within our view so that instead671of _movie.director_ we could use _this.director_.672673 partial('movie', { collection: movies, as: this });674 // In view: this.director675676Another alternative is to "explode" the properties of the collection item into677pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:678679 partials('movie', { collection: movies, as: global });680 // In view: director681682### app.set(name[, val])683684Apply an application level setting _name_ to _val_, or685get the value of _name_ when _val_ is not present:686Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110
lines 687–689why, one step back687 app.set('views', __dirname + '/views');688 app.set('views');689 // => ...path...Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 690–730why, one step back690691### app.enable(name)692693Enable the given setting _name_:694695 app.enable('some arbitrary setting');696 app.set('some arbitrary setting');697 // => true698699### app.disable(name)700701Disable the given setting _name_:702703 app.disable('some setting');704 app.set('some setting');705 // => false706707### app.configure(env|function[, function])708709Define a callback function for the given _env_ (or all environments) with callback _function_:710711 app.configure(function(){712 // executed for each env713 });714715 app.configure('development', function(){716 // executed for 'development' only717 });718719### app.redirect(name, val)720721For use with `res.redirect()` we can map redirects at the application level as shown below:722723 app.redirect('google', 'http://google.com');724725Now in a route we may call:726727 res.redirect('google');728729We may also map dynamic redirects:730Updated docsTj Holowaychukbefore adoptiond691ecb
lines 731–732why, one step back731 app.redirect('comments', function(req, res){732 return '/post/' + req.params.id + '/comments';Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 733–770why, one step back733 });734735So now we may do the following, and the redirect will dynamically adjust to736the context of the request. If we called this route with _GET /post/12_ our737redirect _Location_ would be _/post/12/comments_.738739 app.get('/post/:id', function(req, res){740 res.redirect('comments');741 });742743### app.error(function)744745Adds an error handler _function_ which will receive the exception as the first parameter as shown below.746Note that we may set several error handlers by making several calls to this method, however the handler747should call _next(err)_ if it does not wish to deal with the exception:748749 app.error(function(err, req, res, next){750 res.send(err.message, 500);751 });752753### app.helpers(obj)754755Registers static view helpers.756757 app.helpers({758 name: function(first, last){ return first + ', ' + last },759 firstName: 'tj',760 lastName: 'holowaychuk'761 });762763Our view could now utilize the _firstName_ and _lastName_ variables,764as well as the _name()_ function exposed.765766 <%= name(firstName, lastName) %>767768### app.dynamicHelpers(obj)769770Registers dynamic view helpers. Dynamic view helpersUpdated docsTj Holowaychukbefore adoptiond691ecb
line 771why, one step back771are simply functions which accept _req_, _res_, and areRemoved instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 772–775why, one step back772evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function773becomes the local variable it is associated with.774775 app.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 776why, one step back776 session: function(req, res){Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 777–783why, one step back777 return req.session;778 }779 });780781All views would now have _session_ available so that session data can be accessed via _session.name_ etc:782783 <%= session.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 784–797why, one step back784785### app.mounted(fn)786787Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.788789 var app = express.createServer(),790 blog = express.createServer();791 792 blog.mounted(function(parent){793 // parent is app794 // "this" is blog795 });796 797 app.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 798–822why, one step back798799### app.register(ext, exports)800801Register the given template engine _exports_802as _ext_. For example we may wish to map ".html"803files to jade:804805 app.register('.html', require('jade'));806807This is also useful for libraries that may not808match extensions correctly. For example my haml.js809library is installed from npm as "hamljs" so instead810of layout.hamljs, we can register the engine as ".haml":811812 app.register('.haml', require('haml-js'));813814For engines that do not comply with the Express815specification, we can also wrap their api this way.816817 app.register('.foo', {818 render: function(str, options) {819 // perhaps their api is820 // foo.toHTML(str, options);821 }822 });Removed instanceof Array checkTj Holowaychukbefore adoption0283a73
lines 823–846why, one step back823824### app.listen([port[, host]])825826Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all827connections will be accepted via _INADDR_ANY_.828829 app.listen();830 app.listen(3000);831 app.listen(3000, 'n.n.n.n');832833The _port_ argument may also be a string representing the path to a unix domain socket:834835 app.listen('/tmp/express.sock');836837Then try it out:838839 $ telnet /tmp/express.sock840 GET / HTTP/1.1841842 HTTP/1.1 200 OK843 Content-Type: text/plain844 Content-Length: 11845 846 Hello World