guide.md
This file
Path
docs/guide.md
720 lines · 21.1 KiB · Markdown
Last changed by
Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
History of this fileTake it
The walk stopped after 200 commits: lines older than 1c8ff48 point at it.
More view docsTj Holowaychukbefore adoption1c8ff48
lines 1–3why, one step back12### Installation3No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9
line 4why, one step back4curl:Updated curl install docsTj Holowaychukbefore adoption3ceb0de
lines 5–7why, one step back56 $ curl -# http://expressjs.com/install.sh | sh7More view docsTj Holowaychukbefore adoption1c8ff48
lines 8–40why, one step back8npm: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.More view docsTj Holowaychukbefore adoption1c8ff48
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'));More view docsTj Holowaychukbefore adoption1c8ff48
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 }));More view docsTj Holowaychukbefore adoption1c8ff48
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());More view docsTj Holowaychukbefore adoption1c8ff48
lines 57–81why, 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 });7273To alter the environment we can set the _CONNECT_ENV_ environment variable,74or more specifically _EXPRESS_ENV_, for example:7576 $ EXPRESS_ENV=production node app.js7778### Settings7980Express supports the following settings out of the box:81Updated docsTj Holowaychukbefore adoption4d32762
line 82why, one step back82 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_New "home" docsTj Holowaychukbefore adoption1e7a12f
line 83why, one step back83 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.More view docsTj Holowaychukbefore adoption1c8ff48
lines 84–85why, one step back84 * _views_ Root views directory defaulting to **CWD/views**85 * _view engine_ Default view engine name for views rendered without extensionsMerge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 86why, one step back86 * _view options_ An object specifying global view optionsMerge branch 'integration'Tj Holowaychukbefore adoption3fae10d
line 87why, one step back87 * _partials_ Root view partials directory defaulting to _views_/partials. More view docsTj Holowaychukbefore adoption1c8ff48
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`.More view docsTj Holowaychukbefore adoption1c8ff48
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);More view docsTj Holowaychukbefore adoption1c8ff48
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`.More view docsTj Holowaychukbefore adoption1c8ff48
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"]More view docsTj Holowaychukbefore adoption1c8ff48
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–158why, 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,158and middleware continue to be invoked.More view docsTj Holowaychukbefore adoption1c8ff48
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) {More view docsTj Holowaychukbefore adoption1c8ff48
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){More view docsTj Holowaychukbefore adoption1c8ff48
lines 170–174why, one step back170 // do something else171 });172173### Middleware174Fixed Connect linksTj Holowaychukbefore adoptiona2e93eb
line 175why, one step back175The Express _Plugin_ is no more! middleware via [Connect](http://github.com/senchalabs/connect) can beMore view docsTj Holowaychukbefore adoption1c8ff48
lines 176–177why, one step back176passed to _express.createServer()_ as you would with a regular Connect server. For example:177Updated docsTj Holowaychukbefore adoption344218f
line 178why, one step back178 var express = require('express');More view docsTj Holowaychukbefore adoption1c8ff48
lines 179–180why, one step back179180 var app = express.createServer(Updated docsTj Holowaychukbefore adoption344218f
lines 181–182why, one step back181 express.logger(),182 express.bodyDecoder()More view docsTj Holowaychukbefore adoption1c8ff48
lines 183–186why, one step back183 );184185Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:186Updated docsTj Holowaychukbefore adoption344218f
line 187why, one step back187 app.use(express.logger({ format: ':method :uri' }));More view docsTj Holowaychukbefore adoption1c8ff48
line 188why, one step back188Updated docsTj Holowaychukbefore adoption344218f
lines 189–197why, one step back189Typically with connect middleware you would _require('connect')_ like so:190191 var connect = require('connect');192 app.use(connect.logger());193194This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:195196 app.use(express.logger());197More view docsTj Holowaychukbefore adoption1c8ff48
lines 198–223why, one step back198### Error Handling199200Express provides the _app.error()_ method which receives exceptions thrown within a route,201or passed to _next(err)_. Below is an example which serves different pages based on our202ad-hoc _NotFound_ exception:203204 function NotFound(msg){205 this.name = 'NotFound';206 Error.call(this, msg);207 Error.captureStackTrace(this, arguments.callee);208 }209210 sys.inherits(NotFound, Error);211212 app.get('/404', function(req, res){213 throw new NotFound;214 });215216 app.get('/500', function(req, res){217 throw new Error('keyboard cat!');218 });219220We can call _app.error()_ several times as shown below.221Here we check for an instanceof _NotFound_ and show the222404 page, or we pass on to the next error handler.223Merge branch 'fix-error'Tj Holowaychukbefore adoption498115d
lines 224–228why, one step back224Note that these handlers can be defined anywhere, as they225will be placed below the route handlers on _listen()_. This 226allows for definition within _configure()_ blocks so we can227handle exceptions in different ways based on the environment.228More view docsTj Holowaychukbefore adoption1c8ff48
lines 229–251why, one step back229 app.error(function(err, req, res, next){230 if (err instanceof NotFound) {231 res.render('404.jade');232 } else {233 next(err);234 }235 });236237Here we assume all errors as 500 for the simplicity of238this demo, however you can choose whatever you like239240 app.error(function(err, req, res){241 res.render('500.jade', {242 locals: {243 error: err244 } 245 });246 });247248Our apps could also utilize the Connect _errorHandler_ middleware249to report on exceptions. For example if we wish to output exceptions 250in "development" mode to _stderr_ we can use:251Updated docsTj Holowaychukbefore adoption344218f
line 252why, one step back252 app.use(express.errorHandler({ dumpExceptions: true }));More view docsTj Holowaychukbefore adoption1c8ff48
lines 253–256why, one step back253254Also during development we may want fancy html pages to show exceptions255that are passed or thrown, so we can set _showStack_ to true:256Updated docsTj Holowaychukbefore adoption344218f
line 257why, one step back257 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));More view docsTj Holowaychukbefore adoption1c8ff48
lines 258–265why, one step back258259The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_260is present, which is useful for developing apps that rely heavily on client-side JavaScript.261262### View Rendering263264View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name265of the module that will be required. For example the view _layout.ejs_ willAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 266–267why, one step back266tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 267_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.More view docsTj Holowaychukbefore adoption1c8ff48
lines 268–278why, one step back268269Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,270and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 271the _body_ local variable in _layout.haml_.272273 app.get('/', function(req, res){274 res.render('index.haml', {275 locals: { title: 'My Site' }276 });277 });278Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
lines 279–295why, one step back279The new _view engine_ setting allows us to specify our default template engine,280so for example when using [Jade](http://github.com/visionmedia/jade) we could set:281282 app.set('view engine', 'jade');283284Allowing us to render with:285286 res.render('index');287288vs:289290 res.render('index.jade');291292When _view engine_ is set, extensions are entirely optional, however we can still293mix and match template engines:294295 res.render('another-page.ejs');Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 296–312why, one step back296297Express 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:298299 app.set('view options', {300 layout: false301 });302303Which can then be overridden within the `res.render()` call if need be:304305 res.render('myview.ejs', { layout: true });306307A good example of this is specifying custom _ejs_ opening and closing tags:308309 app.set('view options', {310 open: '{{',311 close: '}}'312 });Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
line 313why, one step back313More view docsTj Holowaychukbefore adoption1c8ff48
lines 314–331why, one step back314### View Partials315316The Express view system has built-in support for partials and collections, which are317sort of "mini" views representing a document fragment. For example rather than iterating318in a view to display comments, we would use a partial with collection support:319320 partial('comment.haml', { collection: comments });321322To make things even less verbose we can assume the extension as _.haml_ when omitted,323however if we wished we could use an ejs partial, within a haml view for example.324325 partial('comment', { collection: comments });326327And once again even further, when rendering a collection we can simply pass328an array, if no other options are desired:329330 partial('comments', comments);331Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701
lines 332–336why, one step back332When using the partial collection support a few "magic" variables are provided333for free:334335 * _firstInCollection_ True if this is the first object336 * _indexInCollection_ Index of the object in the collectionDoc typosTj Holowaychukbefore adoption02b4ec0
line 337why, one step back337 * _lastInCollection_ True if this is the last objectAdded partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701
line 338why, one step back338More view docsTj Holowaychukbefore adoption1c8ff48
lines 339–342why, one step back339### Template Engines340341Below are a few template engines commonly used with Express:342Doc typosTj Holowaychukbefore adoption02b4ec0
lines 343–344why, one step back343 * [Jade](http://jade-lang.com) haml.js successor344 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templatesMore view docsTj Holowaychukbefore adoption1c8ff48
lines 345–382why, one step back345 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript346347### req.header(key[, defaultValue])348349Get the case-insensitive request header _key_, with optional _defaultValue_:350351 req.header('Host');352 req.header('host');353 req.header('Accept', '*/*');354355### req.accepts(type)356357Check if the _Accept_ header is present, and includes the given _type_.358359When the _Accept_ header is not present _true_ is returned. Otherwise360the given _type_ is matched by an exact match, and then subtypes. You361may pass the subtype such as "html" which is then converted internally362to "text/html" using the mime lookup table.363364 // Accept: text/html365 req.accepts('html');366 // => true367368 // Accept: text/*; application/json369 req.accepts('html');370 req.accepts('text/html');371 req.accepts('text/plain');372 req.accepts('application/json');373 // => true374375 req.accepts('image/png');376 req.accepts('png');377 // => false378379### req.param(name)380381Return the value of param _name_ when present.382Updated docsTj Holowaychukbefore adoptiond691ecb
lines 383–385why, one step back383 - Checks route placeholders (_req.params_), ex: /user/:id384 - Checks query string params (_req.query_), ex: ?id=12385 - Checks urlencoded body params (_req.body_), ex: id=12More view docsTj Holowaychukbefore adoption1c8ff48
lines 386–388why, one step back386387To utilize urlencoded request bodies, _req.body_388should be an object. This can be done by usingUpdated docsTj Holowaychukbefore adoption344218f
line 389why, one step back389the _express.bodyDecoder_ middleware.More view docsTj Holowaychukbefore adoption1c8ff48
lines 390–408why, one step back390391### req.flash(type[, msg])392393Queue flash _msg_ of the given _type_.394395 req.flash('info', 'email sent');396 req.flash('error', 'email delivery failed');397 req.flash('info', 'email re-sent');398 // => 2399400 req.flash('info');401 // => ['email sent', 'email re-sent']402403 req.flash('info');404 // => []405406 req.flash();407 // => { error: ['email delivery failed'], info: [] }408Added flash formatter docsTj Holowaychukbefore adoptionf16978d
lines 409–412why, one step back409Flash notification message may also utilize formatters, by default only the %s string formatter is available:410411 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);412More view docsTj Holowaychukbefore adoption1c8ff48
lines 413–453why, one step back413### req.isXMLHttpRequest414415Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header416to see if it was issued by an _XMLHttpRequest_:417418 req.xhr419 req.isXMLHttpRequest420421### res.header(key[, val])422423Get or set the response header _key_.424425 res.header('Content-Length');426 // => undefined427428 res.header('Content-Length', 123);429 // => 123430431 res.header('Content-Length');432 // => 123433434### res.contentType(type)435436Sets the _Content-Type_ response header to the given _type_.437438 var filename = 'path/to/image.png';439 res.contentType(filename);440 // res.headers['Content-Type'] is now "image/png"441442### res.attachment([filename])443444Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.445446 res.attachment('path/to/my/image.png');447448### res.sendfile(path)449450Used by `res.download()` to transfer an arbitrary file. 451452 res.sendfile('path/to/my.file');453Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1
lines 454–457why, one step back454This is _not_ a substitution for Connect's _staticProvider_ middleware, it does not455support HTTP caching, and does not perform any security checks. This method is utilized456by _res.download()_ to transfer static files, and allows you do to so from outside of457the public directory, so suitable security checks should be applied.More view docsTj Holowaychukbefore adoption1c8ff48
lines 458–476why, one step back458459### res.download(file[, filename])460461Transfer the given _file_ as an attachment with optional alternative _filename_.462463 res.download('path/to/image.png');464 res.download('path/to/image.png', 'foo.png');465466This is equivalent to:467468 res.attachment(file);469 res.sendfile(file);470471### res.send(body|status[, headers|status[, status]])472473The `res.send()` method is a high level response utility allowing you to pass474objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status475code based responses. The following are all valid uses:476Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
line 477why, one step back477 res.send(); // 204More view docsTj Holowaychukbefore adoption1c8ff48
lines 478–514why, one step back478 res.send(new Buffer('wahoo'));479 res.send({ some: 'json' });480 res.send('<p>some html</p>');481 res.send('Sorry, cant find that', 404);482 res.send('text', { 'Content-Type': 'text/plain' }, 201);483 res.send(404);484485By default the _Content-Type_ response header is set, however if explicitly486assigned through `res.send()` or previously with `res.header()` or `res.contentType()`487it will not be set again.488489### res.redirect(url[, status])490491Redirect to the given _url_ with a default response _status_ of 302.492493 res.redirect('/', 301);494 res.redirect('/account');495 res.redirect('http://google.com');496 res.redirect('home');497 res.redirect('back');498499Express supports "redirect mapping", which by default provides _home_, and _back_.500The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes501the "home" setting and defaults to "/".502503### res.render(view[, options[, fn]])504505Render _view_ with the given _options_ and optional callback _fn_.506When a callback function is given a response will _not_ be made507automatically, however otherwise a response of _200_ and _text/html_ is given.508509 Most engines accept one or more of the following options,510 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:511512 - _context|scope_ Template evaluation context (_this_)513 - _locals_ Object containing local variables514 - _debug_ Output debugging informationMerge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
lines 515–516why, one step back515 - _status_ Response status code, defaults to 200516 - _headers_ Response headers objectMore view docsTj Holowaychukbefore adoption1c8ff48
line 517why, one step back517In depth partial docsTj Holowaychukbefore adoption793943f
lines 518–555why, one step back518### res.partial(view[, options])519520Render _view_ partial with the given _options_. This method is always available521to the view as a local variable.522523- _as_ Variable name for each _collection_ value, defaults to the view name.524 * as: 'something' will add the _something_ local variable525 * as: this will use the collection value as the template context526 * as: global will merge the collection value's properties with _locals_527528- _collection_ Array of objects, the name is derived from the view name itself. 529 For example _video.html_ will have a object _video_ available to it.530531The following are equivalent, and the name of collection value when passed532to the partial will be _movie_ as derived from the name.533534 partial('movie.jade', { collection: movies });535 partial('movie.jade', movies);536 partial('movie', movies);537 // In view: movie.director538539To change the local from _movie_ to _video_ we can use the "as" option:540541 partial('movie', { collection: movies, as: 'video' });542 // In view: video.director543544Also we can make our movie the value of _this_ within our view so that instead545of _movie.director_ we could use _this.director_.546547 partial('movie', { collection: movies, as: this });548 // In view: this.director549550Another alternative is to "explode" the properties of the collection item into551pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:552553 partials('movie', { collection: movies, as: global });554 // In view: director555More view docsTj Holowaychukbefore adoption1c8ff48
lines 556–560why, one step back556### app.set(name[, val])557558Apply an application level setting _name_ to _val_, or559get the value of _name_ when _val_ is not present:560Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110
lines 561–563why, one step back561 app.set('views', __dirname + '/views');562 app.set('views');563 // => ...path...More view docsTj Holowaychukbefore adoption1c8ff48
lines 564–604why, one step back564565### app.enable(name)566567Enable the given setting _name_:568569 app.enable('some arbitrary setting');570 app.set('some arbitrary setting');571 // => true572573### app.disable(name)574575Disable the given setting _name_:576577 app.disable('some setting');578 app.set('some setting');579 // => false580581### app.configure(env|function[, function])582583Define a callback function for the given _env_ (or all environments) with callback _function_:584585 app.configure(function(){586 // executed for each env587 });588589 app.configure('development', function(){590 // executed for 'development' only591 });592593### app.redirect(name, val)594595For use with `res.redirect()` we can map redirects at the application level as shown below:596597 app.redirect('google', 'http://google.com');598599Now in a route we may call:600601 res.redirect('google');602603We may also map dynamic redirects:604Updated docsTj Holowaychukbefore adoptiond691ecb
lines 605–606why, one step back605 app.redirect('comments', function(req, res){606 return '/post/' + req.params.id + '/comments';More view docsTj Holowaychukbefore adoption1c8ff48
lines 607–625why, one step back607 });608609So now we may do the following, and the redirect will dynamically adjust to610the context of the request. If we called this route with _GET /post/12_ our611redirect _Location_ would be _/post/12/comments_.612613 app.get('/post/:id', function(req, res){614 res.redirect('comments');615 });616617### app.error(function)618619Adds an error handler _function_ which will receive the exception as the first parameter as shown below.620Note that we may set several error handlers by making several calls to this method, however the handler621should call _next(err)_ if it does not wish to deal with the exception:622623 app.error(function(err, req, res, next){624 res.send(err.message, 500);625 });Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 626–628why, one step back626627### app.helpers(obj)628Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 629–644why, one step back629Registers static view helpers.630631 app.helpers({632 name: function(first, last){ return first + ', ' + last },633 firstName: 'tj',634 lastName: 'holowaychuk'635 });636637Our view could now utilize the _firstName_ and _lastName_ variables,638as well as the _name()_ function exposed.639640 <%= name(firstName, lastName) %>641642### app.dynamicHelpers(obj)643644Registers dynamic view helpers. Dynamic view helpersUpdated docsTj Holowaychukbefore adoptiond691ecb
line 645why, one step back645are simply functions which accept _req_, _res_, and areDocs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 646why, one step back646evaluated against the _Server_ instance before a view is rendered. The _return value_ of this functionAdded app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 647–648why, one step back647becomes the local variable it is associated with.648Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 649why, one step back649 app.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 650why, one step back650 session: function(req, res){Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 651–654why, one step back651 return req.session;652 }653 });654Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 655–657why, one step back655All views would now have _session_ available so that session data can be accessed via _session.name_ etc:656657 <%= session.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 658–671why, one step back658659### app.mounted(fn)660661Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.662663 var app = express.createServer(),664 blog = express.createServer();665 666 blog.mounted(function(parent){667 // parent is app668 // "this" is blog669 });670 671 app.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 672–696why, one step back672673### app.register(ext, exports)674675Register the given template engine _exports_676as _ext_. For example we may wish to map ".html"677files to jade:678679 app.register('.html', require('jade'));680681This is also useful for libraries that may not682match extensions correctly. For example my haml.js683library is installed from npm as "hamljs" so instead684of layout.hamljs, we can register the engine as ".haml":685686 app.register('.haml', require('haml-js'));687688For engines that do not comply with the Express689specification, we can also wrap their api this way.690691 app.register('.foo', {692 render: function(str, options) {693 // perhaps their api is694 // foo.toHTML(str, options);695 }696 });More view docsTj Holowaychukbefore adoption1c8ff48
lines 697–720why, one step back697698### app.listen([port[, host]])699700Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all701connections will be accepted via _INADDR_ANY_.702703 app.listen();704 app.listen(3000);705 app.listen(3000, 'n.n.n.n');706707The _port_ argument may also be a string representing the path to a unix domain socket:708709 app.listen('/tmp/express.sock');710711Then try it out:712713 $ telnet /tmp/express.sock714 GET / HTTP/1.1715716 HTTP/1.1 200 OK717 Content-Type: text/plain718 Content-Length: 11719 720 Hello World