guide.md
This file
Path
docs/guide.md
659 lines · 19.1 KiB · Markdown
Last changed by
Undocumented cache optionTj Holowaychukbefore adoption74b3921
History of this fileTake it
The walk stopped after 200 commits: lines older than fce527a point at it.
Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
line 1why, one step back1Install docsTj Holowaychukbefore adoption63d02f1
lines 2–3why, one step back2### 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 | sh7Install docsTj Holowaychukbefore adoption63d02f1
lines 8–11why, one step back8npm:910 $ npm install express11Updated install docsTj Holowaychukbefore adoption193c4a9
line 12why, one step back12git clone, first update the submodules:Install docsTj Holowaychukbefore adoption63d02f1
line 13why, one step back13Updated install docsTj Holowaychukbefore adoption193c4a9
line 14why, one step back14 $ git submodule update --initInstall docsTj Holowaychukbefore adoption63d02f1
line 15why, one step back15 $ make installUpdated install docsTj Holowaychukbefore adoption193c4a9
line 16why, one step back16 $ make install-supportInstall docsTj Holowaychukbefore adoption63d02f1
line 17why, one step back17Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
lines 18–40why, one step back18### 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.Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
lines 43–44why, one step back4344 app.configure(function(){Updated docsTj Holowaychukbefore adoptioncacada8
lines 45–46why, one step back45 app.use(connect.methodOverride());46 app.use(connect.bodyDecoder());Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
lines 47–48why, one step back47 app.use(app.router);48 app.use(connect.staticProvider(__dirname + '/public'));Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
lines 49–51why, one step back49 });50 51 app.configure('development', function(){Updated docsTj Holowaychukbefore adoptioncacada8
line 52why, one step back52 app.use(connect.errorHandler({ dumpExceptions: true, showStack: true }));Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
lines 53–55why, one step back53 });54 55 app.configure('production', function(){Updated docsTj Holowaychukbefore adoptioncacada8
line 56why, one step back56 app.use(connect.errorHandler());Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
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 });72More docsTj Holowaychukbefore adoptionde81ee7
lines 73–77why, one step back73To alter the environment we can set the _CONNECT_ENV_ environment variable,74or more specifically _EXPRESS_ENV_, for example:7576 $ EXPRESS_ENV=production node app.js77Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
lines 78–81why, one step back78### 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.Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
lines 84–86why, one step back84 * _views_ Root views directory defaulting to **CWD/views**85 * _view engine_ Default view engine name for views rendered without extensions86 * _reload views_ Reloads altered views, by default watches for _mtime_ changes withDefaulting app.enable("reload views") to 500msTj Holowaychukbefore adoption7a1525c
line 87why, one step back87 with a 500 millisecond interval.Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
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`.Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
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);Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
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`.Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
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"]Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
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.Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
line 159why, one step back159Updated docsTj Holowaychukbefore adoptiond691ecb
lines 160–162why, one step back160 app.get('/users/:id?', function(req, res){161 var id = req.params.id;162 if (id) {Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
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){Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
lines 170–185why, one step back170 // do something else171 });172173### Middleware174175The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be176passed to _express.createServer()_ as you would with a regular Connect server. For example:177178 var connect = require('connect'),179 express = require('express');180181 var app = express.createServer(182 connect.logger(),183 connect.bodyDecoder()184 );185Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 186–187why, one step back186Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:187Updated docsTj Holowaychukbefore adoptioncacada8
line 188why, one step back188 app.use(connect.logger({ format: ':method :uri' }));Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 189–234why, one step back189190### Error Handling191192Express provides the _app.error()_ method which receives exceptions thrown within a route,193or passed to _next(err)_. Below is an example which serves different pages based on our194ad-hoc _NotFound_ exception:195196 function NotFound(msg){197 this.name = 'NotFound';198 Error.call(this, msg);199 Error.captureStackTrace(this, arguments.callee);200 }201202 sys.inherits(NotFound, Error);203204 app.get('/404', function(req, res){205 throw new NotFound;206 });207208 app.get('/500', function(req, res){209 throw new Error('keyboard cat!');210 });211212We can call _app.error()_ several times as shown below.213Here we check for an instanceof _NotFound_ and show the214404 page, or we pass on to the next error handler.215216 app.error(function(err, req, res, next){217 if (err instanceof NotFound) {218 res.render('404.jade');219 } else {220 next(err);221 }222 });223224Here we assume all errors as 500 for the simplicity of225this demo, however you can choose whatever you like226227 app.error(function(err, req, res){228 res.render('500.jade', {229 locals: {230 error: err231 } 232 });233 });234More error handling docsTj Holowaychukbefore adoptioncea401c
lines 235–238why, one step back235Our apps could also utilize the Connect _errorHandler_ middleware236to report on exceptions. For example if we wish to output exceptions 237in "development" mode to _stderr_ we can use:238Updated docsTj Holowaychukbefore adoptioncacada8
line 239why, one step back239 app.use(connect.errorHandler({ dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 240–243why, one step back240241Also during development we may want fancy html pages to show exceptions242that are passed or thrown, so we can set _showStack_ to true:243Updated docsTj Holowaychukbefore adoptioncacada8
line 244why, one step back244 app.use(connect.errorHandler({ showStack: true, dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 245–248why, one step back245246The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_247is present, which is useful for developing apps that rely heavily on client-side JavaScript.248Added more view docsTj Holowaychukbefore adoption2f96506
lines 249–266why, one step back249### View Rendering250251View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name252of the module that will be required. For example the view _layout.ejs_ will253tell the view system to _require('ejs')_, the module being loaded must (currently)254export the method _exports.render(str, options)_ to comply with Express, however 255with will likely be extensible in the future.256257Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,258and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 259the _body_ local variable in _layout.haml_.260261 app.get('/', function(req, res){262 res.render('index.haml', {263 locals: { title: 'My Site' }264 });265 });266Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
lines 267–284why, one step back267The new _view engine_ setting allows us to specify our default template engine,268so for example when using [Jade](http://github.com/visionmedia/jade) we could set:269270 app.set('view engine', 'jade');271272Allowing us to render with:273274 res.render('index');275276vs:277278 res.render('index.jade');279280When _view engine_ is set, extensions are entirely optional, however we can still281mix and match template engines:282283 res.render('another-page.ejs');284Added more view docsTj Holowaychukbefore adoption2f96506
lines 285–302why, one step back285### View Partials286287The Express view system has built-in support for partials and collections, which are288sort of "mini" views representing a document fragment. For example rather than iterating289in a view to display comments, we would use a partial with collection support:290291 partial('comment.haml', { collection: comments });292293To make things even less verbose we can assume the extension as _.haml_ when omitted,294however if we wished we could use an ejs partial, within a haml view for example.295296 partial('comment', { collection: comments });297298And once again even further, when rendering a collection we can simply pass299an array, if no other options are desired:300301 partial('comments', comments);302Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701
lines 303–309why, one step back303When using the partial collection support a few "magic" variables are provided304for free:305306 * _firstInCollection_ True if this is the first object307 * _indexInCollection_ Index of the object in the collection308 * _lastInCollection _ True if this is the last object309Added more view docsTj Holowaychukbefore adoption2f96506
lines 310–317why, one step back310### Template Engines311312Below are a few template engines commonly used with Express:313314 * [Jade](http://github.com/visionmedia/jade) haml.js successor315 * [Haml](http://github.com/visionmedia/haml.js) indented templates316 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript317More docsTj Holowaychukbefore adoptionde81ee7
line 318why, one step back318### req.header(key[, defaultValue])More docsTj Holowaychukbefore adoptiondfecbe5
lines 319–325why, one step back319320Get the case-insensitive request header _key_, with optional _defaultValue_:321322 req.header('Host');323 req.header('host');324 req.header('Accept', '*/*');325More docsTj Holowaychukbefore adoptionde81ee7
line 326why, one step back326### req.accepts(type)More docsTj Holowaychukbefore adoptiondfecbe5
lines 327–349why, one step back327328Check if the _Accept_ header is present, and includes the given _type_.329330When the _Accept_ header is not present _true_ is returned. Otherwise331the given _type_ is matched by an exact match, and then subtypes. You332may pass the subtype such as "html" which is then converted internally333to "text/html" using the mime lookup table.334335 // Accept: text/html336 req.accepts('html');337 // => true338339 // Accept: text/*; application/json340 req.accepts('html');341 req.accepts('text/html');342 req.accepts('text/plain');343 req.accepts('application/json');344 // => true345346 req.accepts('image/png');347 req.accepts('png');348 // => false349More docsTj Holowaychukbefore adoptionde81ee7
line 350why, one step back350### req.param(name)More docsTj Holowaychukbefore adoptiondfecbe5
lines 351–353why, one step back351352Return the value of param _name_ when present.353Updated docsTj Holowaychukbefore adoptiond691ecb
lines 354–356why, one step back354 - Checks route placeholders (_req.params_), ex: /user/:id355 - Checks query string params (_req.query_), ex: ?id=12356 - Checks urlencoded body params (_req.body_), ex: id=12More docsTj Holowaychukbefore adoptiondfecbe5
lines 357–361why, one step back357358To utilize urlencoded request bodies, _req.body_359should be an object. This can be done by using360the _connect.bodyDecoder_ middleware.361More docsTj Holowaychukbefore adoptionde81ee7
line 362why, one step back362### req.flash(type[, msg])More docsTj Holowaychukbefore adoptiondfecbe5
lines 363–379why, one step back363364Queue flash _msg_ of the given _type_.365366 req.flash('info', 'email sent');367 req.flash('error', 'email delivery failed');368 req.flash('info', 'email re-sent');369 // => 2370371 req.flash('info');372 // => ['email sent', 'email re-sent']373374 req.flash('info');375 // => []376377 req.flash();378 // => { error: ['email delivery failed'], info: [] }379More docsTj Holowaychukbefore adoptionde81ee7
line 380why, one step back380### req.isXMLHttpRequestMore docsTj Holowaychukbefore adoptiondfecbe5
lines 381–387why, one step back381382Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header383to see if it was issued by an _XMLHttpRequest_:384385 req.xhr386 req.isXMLHttpRequest387More docsTj Holowaychukbefore adoptionde81ee7
line 388why, one step back388### res.header(key[, val])More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 389–400why, one step back389390Get or set the response header _key_.391392 res.header('Content-Length');393 // => undefined394395 res.header('Content-Length', 123);396 // => 123397398 res.header('Content-Length');399 // => 123400More docsTj Holowaychukbefore adoptionde81ee7
line 401why, one step back401### res.contentType(type)More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 402–408why, one step back402403Sets the _Content-Type_ response header to the given _type_.404405 var filename = 'path/to/image.png';406 res.contentType(filename);407 // res.headers['Content-Type'] is now "image/png"408More docsTj Holowaychukbefore adoptionde81ee7
line 409why, one step back409### res.attachment([filename])Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
lines 410–414why, one step back410411Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.412413 res.attachment('path/to/my/image.png');414More docsTj Holowaychukbefore adoptionde81ee7
line 415why, one step back415### res.sendfile(path)Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 416–420why, one step back416417Used by `res.download()` to transfer an arbitrary file. 418419 res.sendfile('path/to/my.file');420Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1
lines 421–424why, one step back421This is _not_ a substitution for Connect's _staticProvider_ middleware, it does not422support HTTP caching, and does not perform any security checks. This method is utilized423by _res.download()_ to transfer static files, and allows you do to so from outside of424the public directory, so suitable security checks should be applied.Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
line 425why, one step back425More docsTj Holowaychukbefore adoptionde81ee7
line 426why, one step back426### res.download(file[, filename])Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 427–437why, one step back427428Transfer the given _file_ as an attachment with optional alternative _filename_.429430 res.download('path/to/image.png');431 res.download('path/to/image.png', 'foo.png');432433This is equivalent to:434435 res.attachment(file);436 res.sendfile(file);437More docsTj Holowaychukbefore adoptionde81ee7
line 438why, one step back438### res.send(body|status[, headers|status[, status]])Docs for res.send()Tj Holowaychukbefore adoption5a48248
lines 439–454why, one step back439440The `res.send()` method is a high level response utility allowing you to pass441objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status442code based responses. The following are all valid uses:443444 res.send(new Buffer('wahoo'));445 res.send({ some: 'json' });446 res.send('<p>some html</p>');447 res.send('Sorry, cant find that', 404);448 res.send('text', { 'Content-Type': 'text/plain' }, 201);449 res.send(404);450451By default the _Content-Type_ response header is set, however if explicitly452assigned through `res.send()` or previously with `res.header()` or `res.contentType()`453it will not be set again.454More docsTj Holowaychukbefore adoptionde81ee7
line 455why, one step back455### res.redirect(url[, status])Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
line 456why, one step back456More docsTj Holowaychukbefore adoptionbedff32
line 457why, one step back457Redirect to the given _url_ with a default response _status_ of 302.Added progress to multipart exampleTj Holowaychukbefore adoptionfce527a
line 458why, one step back458More docsTj Holowaychukbefore adoptionbedff32
lines 459–468why, one step back459 res.redirect('/', 301);460 res.redirect('/account');461 res.redirect('http://google.com');462 res.redirect('home');463 res.redirect('back');464465Express supports "redirect mapping", which by default provides _home_, and _back_.466The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes467the "home" setting and defaults to "/".468More view docsTj Holowaychukbefore adoption1c8ff48
lines 469–481why, one step back469### res.render(view[, options[, fn]])470471Render _view_ with the given _options_ and optional callback _fn_.472When a callback function is given a response will _not_ be made473automatically, however otherwise a response of _200_ and _text/html_ is given.474475 Most engines accept one or more of the following options,476 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:477478 - _context|scope_ Template evaluation context (_this_)479 - _locals_ Object containing local variables480 - _debug_ Output debugging information481In depth partial docsTj Holowaychukbefore adoption793943f
lines 482–519why, one step back482### res.partial(view[, options])483484Render _view_ partial with the given _options_. This method is always available485to the view as a local variable.486487- _as_ Variable name for each _collection_ value, defaults to the view name.488 * as: 'something' will add the _something_ local variable489 * as: this will use the collection value as the template context490 * as: global will merge the collection value's properties with _locals_491492- _collection_ Array of objects, the name is derived from the view name itself. 493 For example _video.html_ will have a object _video_ available to it.494495The following are equivalent, and the name of collection value when passed496to the partial will be _movie_ as derived from the name.497498 partial('movie.jade', { collection: movies });499 partial('movie.jade', movies);500 partial('movie', movies);501 // In view: movie.director502503To change the local from _movie_ to _video_ we can use the "as" option:504505 partial('movie', { collection: movies, as: 'video' });506 // In view: video.director507508Also we can make our movie the value of _this_ within our view so that instead509of _movie.director_ we could use _this.director_.510511 partial('movie', { collection: movies, as: this });512 // In view: this.director513514Another alternative is to "explode" the properties of the collection item into515pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:516517 partials('movie', { collection: movies, as: global });518 // In view: director519More docsTj Holowaychukbefore adoptionde81ee7
lines 520–557why, one step back520### app.set(name[, val])521522Apply an application level setting _name_ to _val_, or523get the value of _name_ when _val_ is not present:524525 app.set('reload views', 200);526 app.set('reload views');527 // => 200528529### app.enable(name)530531Enable the given setting _name_:532533 app.enable('some arbitrary setting');534 app.set('some arbitrary setting');535 // => true536537### app.disable(name)538539Disable the given setting _name_:540541 app.disable('some setting');542 app.set('some setting');543 // => false544545### app.configure(env|function[, function])546547Define a callback function for the given _env_ (or all environments) with callback _function_:548549 app.configure(function(){550 // executed for each env551 });552553 app.configure('development', function(){554 // executed for 'development' only555 });556557### app.redirect(name, val)More docsTj Holowaychukbefore adoptionbedff32
lines 558–568why, one step back558559For use with `res.redirect()` we can map redirects at the application level as shown below:560561 app.redirect('google', 'http://google.com');562563Now in a route we may call:564565 res.redirect('google');566567We may also map dynamic redirects:568Updated docsTj Holowaychukbefore adoptiond691ecb
lines 569–570why, one step back569 app.redirect('comments', function(req, res){570 return '/post/' + req.params.id + '/comments';More docsTj Holowaychukbefore adoptionbedff32
lines 571–579why, one step back571 });572573So now we may do the following, and the redirect will dynamically adjust to574the context of the request. If we called this route with _GET /post/12_ our575redirect _Location_ would be _/post/12/comments_.576577 app.get('/post/:id', function(req, res){578 res.redirect('comments');579 });Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 580–582why, one step back580581### app.error(function)582More error docsTj Holowaychukbefore adoption6227f5c
lines 583–585why, one step back583Adds an error handler _function_ which will receive the exception as the first parameter as shown below.584Note that we may set several error handlers by making several calls to this method, however the handler585should call _next(err)_ if it does not wish to deal with the exception:Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 586–589why, one step back586587 app.error(function(err, req, res, next){588 res.send(err.message, 500);589 });Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 590–592why, one step back590591### app.helpers(obj)592Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 593–608why, one step back593Registers static view helpers.594595 app.helpers({596 name: function(first, last){ return first + ', ' + last },597 firstName: 'tj',598 lastName: 'holowaychuk'599 });600601Our view could now utilize the _firstName_ and _lastName_ variables,602as well as the _name()_ function exposed.603604 <%= name(firstName, lastName) %>605606### app.dynamicHelpers(obj)607608Registers dynamic view helpers. Dynamic view helpersUpdated docsTj Holowaychukbefore adoptiond691ecb
line 609why, one step back609are simply functions which accept _req_, _res_, and areDocs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 610why, one step back610evaluated against the _Server_ instance before a view is rendered. The _return value_ of this functionAdded app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 611–612why, one step back611becomes the local variable it is associated with.612Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 613why, one step back613 app.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 614why, one step back614 session: function(req, res){Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 615–618why, one step back615 return req.session;616 }617 });618Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 619–621why, one step back619All views would now have _session_ available so that session data can be accessed via _session.name_ etc:620621 <%= session.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 622–635why, one step back622623### app.mounted(fn)624625Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.626627 var app = express.createServer(),628 blog = express.createServer();629 630 blog.mounted(function(parent){631 // parent is app632 // "this" is blog633 });634 635 app.use(blog);Server#listen() docsTj Holowaychukbefore adoptionf3803c4
lines 636–644why, one step back636637### app.listen([port[, host]])638639Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all640connections will be accepted via _INADDR_ANY_.641642 app.listen();643 app.listen(3000);644 app.listen(3000, 'n.n.n.n');Unix domain socket docsTj Holowaychukbefore adoption2fa7907
lines 645–659why, one step back645646The _port_ argument may also be a string representing the path to a unix domain socket:647648 app.listen('/tmp/express.sock');649650Then try it out:651652 $ telnet /tmp/express.sock653 GET / HTTP/1.1654655 HTTP/1.1 200 OK656 Content-Type: text/plain657 Content-Length: 11658 659 Hello World