guide.md
This file
Path
docs/guide.md
657 lines · 19.0 KiB · Markdown
Last changed by
Fixed doc typoTj Holowaychukbefore adoption47ff7d9
History of this fileTake it
The walk stopped after 200 commits: lines older than df7582b point at it.
TasksTj Holowaychukbefore adoptiondf7582b
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 back17TasksTj Holowaychukbefore adoptiondf7582b
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.TasksTj Holowaychukbefore adoptiondf7582b
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'));TasksTj Holowaychukbefore adoptiondf7582b
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 }));TasksTj Holowaychukbefore adoptiondf7582b
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());TasksTj Holowaychukbefore adoptiondf7582b
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.js77TasksTj Holowaychukbefore adoptiondf7582b
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.TasksTj Holowaychukbefore adoptiondf7582b
lines 84–90why, one step back84 * _views_ Root views directory defaulting to **CWD/views**85 * _view engine_ Default view engine name for views rendered without extensions8687### Routing8889Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.90For example we may want to render a user's account for the path _/user/12_, thisUpdated docsTj Holowaychukbefore adoptiond691ecb
lines 91–92why, one step back91can be done by defining the route below. The values associated to the named placeholders 92are available as `req.params`.TasksTj Holowaychukbefore adoptiondf7582b
line 93why, one step back93Updated docsTj Holowaychukbefore adoptiond691ecb
lines 94–95why, one step back94 app.get('/user/:id', function(req, res){95 res.send('user ' + req.params.id);TasksTj Holowaychukbefore adoptiondf7582b
lines 96–102why, one step back96 });9798A route is simple a string which is compiled to a _RegExp_ internally. For example99when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:100101 \/user\/([^\/]+)\/?102Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
line 103why, one step back103Regular expression literals may also be passed for complex uses. Since captureUpdated docsTj Holowaychukbefore adoptiond691ecb
line 104why, one step back104groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.TasksTj Holowaychukbefore adoptiondf7582b
line 105why, one step back105Updated docsTj Holowaychukbefore adoptiond691ecb
lines 106–107why, one step back106 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){107 res.send(req.params);Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
lines 108–119why, one step back108 });109110Curl requests against the previously defined route:111112 $ curl http://dev:3000/user113 [null,null]114 $ curl http://dev:3000/users115 [null,null]116 $ curl http://dev:3000/users/1117 ["1",null]118 $ curl http://dev:3000/users/1..15119 ["1","15"]TasksTj Holowaychukbefore adoptiondf7582b
lines 120–153why, one step back120121Below are some route examples, and the associated paths that they122may consume:123124 "/user/:id"125 /user/12126127 "/users/:id?"128 /users/5129 /users130131 "/files/*"132 /files/jquery.js133 /files/javascripts/jquery.js134135 "/file/*.*"136 /files/jquery.js137 /files/javascripts/jquery.js138 139 "/user/:id/:operation?"140 /user/1141 /user/1/edit142 143 "/products.:format"144 /products.json145 /products.xml146147 "/products.:format?"148 /products.json149 /products.xml150 /products151152### Passing Route Control153Updated docsTj Holowaychukbefore adoptiond691ecb
lines 154–156why, one step back154We may pass control to the next _matching_ route, by calling the _third_ argument,155the _next()_ function. When a match cannot be made, control is passed back to Connect,156and middleware continue to be invoked.TasksTj Holowaychukbefore adoptiondf7582b
line 157why, one step back157Fixed doc typoTj Holowaychukbefore adoption47ff7d9
line 158why, one step back158 app.get('/users/:id?', function(req, res, next){Updated docsTj Holowaychukbefore adoptiond691ecb
lines 159–160why, one step back159 var id = req.params.id;160 if (id) {TasksTj Holowaychukbefore adoptiondf7582b
lines 161–166why, one step back161 // do something162 } else {163 next();164 }165 });166 Updated docsTj Holowaychukbefore adoptiond691ecb
line 167why, one step back167 app.get('/users', function(req, res){TasksTj Holowaychukbefore adoptiondf7582b
lines 168–183why, one step back168 // do something else169 });170171### Middleware172173The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be174passed to _express.createServer()_ as you would with a regular Connect server. For example:175176 var connect = require('connect'),177 express = require('express');178179 var app = express.createServer(180 connect.logger(),181 connect.bodyDecoder()182 );183Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 184–185why, one step back184Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:185Updated docsTj Holowaychukbefore adoptioncacada8
line 186why, one step back186 app.use(connect.logger({ format: ':method :uri' }));Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 187–232why, one step back187188### Error Handling189190Express provides the _app.error()_ method which receives exceptions thrown within a route,191or passed to _next(err)_. Below is an example which serves different pages based on our192ad-hoc _NotFound_ exception:193194 function NotFound(msg){195 this.name = 'NotFound';196 Error.call(this, msg);197 Error.captureStackTrace(this, arguments.callee);198 }199200 sys.inherits(NotFound, Error);201202 app.get('/404', function(req, res){203 throw new NotFound;204 });205206 app.get('/500', function(req, res){207 throw new Error('keyboard cat!');208 });209210We can call _app.error()_ several times as shown below.211Here we check for an instanceof _NotFound_ and show the212404 page, or we pass on to the next error handler.213214 app.error(function(err, req, res, next){215 if (err instanceof NotFound) {216 res.render('404.jade');217 } else {218 next(err);219 }220 });221222Here we assume all errors as 500 for the simplicity of223this demo, however you can choose whatever you like224225 app.error(function(err, req, res){226 res.render('500.jade', {227 locals: {228 error: err229 } 230 });231 });232More error handling docsTj Holowaychukbefore adoptioncea401c
lines 233–236why, one step back233Our apps could also utilize the Connect _errorHandler_ middleware234to report on exceptions. For example if we wish to output exceptions 235in "development" mode to _stderr_ we can use:236Updated docsTj Holowaychukbefore adoptioncacada8
line 237why, one step back237 app.use(connect.errorHandler({ dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 238–241why, one step back238239Also during development we may want fancy html pages to show exceptions240that are passed or thrown, so we can set _showStack_ to true:241Updated docsTj Holowaychukbefore adoptioncacada8
line 242why, one step back242 app.use(connect.errorHandler({ showStack: true, dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 243–246why, one step back243244The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_245is present, which is useful for developing apps that rely heavily on client-side JavaScript.246Added more view docsTj Holowaychukbefore adoption2f96506
lines 247–264why, one step back247### View Rendering248249View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name250of the module that will be required. For example the view _layout.ejs_ will251tell the view system to _require('ejs')_, the module being loaded must (currently)252export the method _exports.render(str, options)_ to comply with Express, however 253with will likely be extensible in the future.254255Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,256and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 257the _body_ local variable in _layout.haml_.258259 app.get('/', function(req, res){260 res.render('index.haml', {261 locals: { title: 'My Site' }262 });263 });264Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
lines 265–282why, one step back265The new _view engine_ setting allows us to specify our default template engine,266so for example when using [Jade](http://github.com/visionmedia/jade) we could set:267268 app.set('view engine', 'jade');269270Allowing us to render with:271272 res.render('index');273274vs:275276 res.render('index.jade');277278When _view engine_ is set, extensions are entirely optional, however we can still279mix and match template engines:280281 res.render('another-page.ejs');282Added more view docsTj Holowaychukbefore adoption2f96506
lines 283–300why, one step back283### View Partials284285The Express view system has built-in support for partials and collections, which are286sort of "mini" views representing a document fragment. For example rather than iterating287in a view to display comments, we would use a partial with collection support:288289 partial('comment.haml', { collection: comments });290291To make things even less verbose we can assume the extension as _.haml_ when omitted,292however if we wished we could use an ejs partial, within a haml view for example.293294 partial('comment', { collection: comments });295296And once again even further, when rendering a collection we can simply pass297an array, if no other options are desired:298299 partial('comments', comments);300Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701
lines 301–307why, one step back301When using the partial collection support a few "magic" variables are provided302for free:303304 * _firstInCollection_ True if this is the first object305 * _indexInCollection_ Index of the object in the collection306 * _lastInCollection _ True if this is the last object307Added more view docsTj Holowaychukbefore adoption2f96506
lines 308–315why, one step back308### Template Engines309310Below are a few template engines commonly used with Express:311312 * [Jade](http://github.com/visionmedia/jade) haml.js successor313 * [Haml](http://github.com/visionmedia/haml.js) indented templates314 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript315More docsTj Holowaychukbefore adoptionde81ee7
line 316why, one step back316### req.header(key[, defaultValue])More docsTj Holowaychukbefore adoptiondfecbe5
lines 317–323why, one step back317318Get the case-insensitive request header _key_, with optional _defaultValue_:319320 req.header('Host');321 req.header('host');322 req.header('Accept', '*/*');323More docsTj Holowaychukbefore adoptionde81ee7
line 324why, one step back324### req.accepts(type)More docsTj Holowaychukbefore adoptiondfecbe5
lines 325–347why, one step back325326Check if the _Accept_ header is present, and includes the given _type_.327328When the _Accept_ header is not present _true_ is returned. Otherwise329the given _type_ is matched by an exact match, and then subtypes. You330may pass the subtype such as "html" which is then converted internally331to "text/html" using the mime lookup table.332333 // Accept: text/html334 req.accepts('html');335 // => true336337 // Accept: text/*; application/json338 req.accepts('html');339 req.accepts('text/html');340 req.accepts('text/plain');341 req.accepts('application/json');342 // => true343344 req.accepts('image/png');345 req.accepts('png');346 // => false347More docsTj Holowaychukbefore adoptionde81ee7
line 348why, one step back348### req.param(name)More docsTj Holowaychukbefore adoptiondfecbe5
lines 349–351why, one step back349350Return the value of param _name_ when present.351Updated docsTj Holowaychukbefore adoptiond691ecb
lines 352–354why, one step back352 - Checks route placeholders (_req.params_), ex: /user/:id353 - Checks query string params (_req.query_), ex: ?id=12354 - Checks urlencoded body params (_req.body_), ex: id=12More docsTj Holowaychukbefore adoptiondfecbe5
lines 355–359why, one step back355356To utilize urlencoded request bodies, _req.body_357should be an object. This can be done by using358the _connect.bodyDecoder_ middleware.359More docsTj Holowaychukbefore adoptionde81ee7
line 360why, one step back360### req.flash(type[, msg])More docsTj Holowaychukbefore adoptiondfecbe5
lines 361–377why, one step back361362Queue flash _msg_ of the given _type_.363364 req.flash('info', 'email sent');365 req.flash('error', 'email delivery failed');366 req.flash('info', 'email re-sent');367 // => 2368369 req.flash('info');370 // => ['email sent', 'email re-sent']371372 req.flash('info');373 // => []374375 req.flash();376 // => { error: ['email delivery failed'], info: [] }377More docsTj Holowaychukbefore adoptionde81ee7
line 378why, one step back378### req.isXMLHttpRequestMore docsTj Holowaychukbefore adoptiondfecbe5
lines 379–385why, one step back379380Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header381to see if it was issued by an _XMLHttpRequest_:382383 req.xhr384 req.isXMLHttpRequest385More docsTj Holowaychukbefore adoptionde81ee7
line 386why, one step back386### res.header(key[, val])TasksTj Holowaychukbefore adoptiondf7582b
lines 387–398why, one step back387388Get or set the response header _key_.389390 res.header('Content-Length');391 // => undefined392393 res.header('Content-Length', 123);394 // => 123395396 res.header('Content-Length');397 // => 123398More docsTj Holowaychukbefore adoptionde81ee7
line 399why, one step back399### res.contentType(type)TasksTj Holowaychukbefore adoptiondf7582b
lines 400–406why, one step back400401Sets the _Content-Type_ response header to the given _type_.402403 var filename = 'path/to/image.png';404 res.contentType(filename);405 // res.headers['Content-Type'] is now "image/png"406More docsTj Holowaychukbefore adoptionde81ee7
line 407why, one step back407### res.attachment([filename])TasksTj Holowaychukbefore adoptiondf7582b
lines 408–412why, one step back408409Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.410411 res.attachment('path/to/my/image.png');412More docsTj Holowaychukbefore adoptionde81ee7
line 413why, one step back413### res.sendfile(path)TasksTj Holowaychukbefore adoptiondf7582b
lines 414–418why, one step back414415Used by `res.download()` to transfer an arbitrary file. 416417 res.sendfile('path/to/my.file');418Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1
lines 419–422why, one step back419This is _not_ a substitution for Connect's _staticProvider_ middleware, it does not420support HTTP caching, and does not perform any security checks. This method is utilized421by _res.download()_ to transfer static files, and allows you do to so from outside of422the public directory, so suitable security checks should be applied.TasksTj Holowaychukbefore adoptiondf7582b
line 423why, one step back423More docsTj Holowaychukbefore adoptionde81ee7
line 424why, one step back424### res.download(file[, filename])TasksTj Holowaychukbefore adoptiondf7582b
lines 425–435why, one step back425426Transfer the given _file_ as an attachment with optional alternative _filename_.427428 res.download('path/to/image.png');429 res.download('path/to/image.png', 'foo.png');430431This is equivalent to:432433 res.attachment(file);434 res.sendfile(file);435More docsTj Holowaychukbefore adoptionde81ee7
line 436why, one step back436### res.send(body|status[, headers|status[, status]])TasksTj Holowaychukbefore adoptiondf7582b
lines 437–452why, one step back437438The `res.send()` method is a high level response utility allowing you to pass439objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status440code based responses. The following are all valid uses:441442 res.send(new Buffer('wahoo'));443 res.send({ some: 'json' });444 res.send('<p>some html</p>');445 res.send('Sorry, cant find that', 404);446 res.send('text', { 'Content-Type': 'text/plain' }, 201);447 res.send(404);448449By default the _Content-Type_ response header is set, however if explicitly450assigned through `res.send()` or previously with `res.header()` or `res.contentType()`451it will not be set again.452More docsTj Holowaychukbefore adoptionde81ee7
line 453why, one step back453### res.redirect(url[, status])TasksTj Holowaychukbefore adoptiondf7582b
lines 454–466why, one step back454455Redirect to the given _url_ with a default response _status_ of 302.456457 res.redirect('/', 301);458 res.redirect('/account');459 res.redirect('http://google.com');460 res.redirect('home');461 res.redirect('back');462463Express supports "redirect mapping", which by default provides _home_, and _back_.464The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes465the "home" setting and defaults to "/".466More view docsTj Holowaychukbefore adoption1c8ff48
lines 467–479why, one step back467### res.render(view[, options[, fn]])468469Render _view_ with the given _options_ and optional callback _fn_.470When a callback function is given a response will _not_ be made471automatically, however otherwise a response of _200_ and _text/html_ is given.472473 Most engines accept one or more of the following options,474 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:475476 - _context|scope_ Template evaluation context (_this_)477 - _locals_ Object containing local variables478 - _debug_ Output debugging information479In depth partial docsTj Holowaychukbefore adoption793943f
lines 480–517why, one step back480### res.partial(view[, options])481482Render _view_ partial with the given _options_. This method is always available483to the view as a local variable.484485- _as_ Variable name for each _collection_ value, defaults to the view name.486 * as: 'something' will add the _something_ local variable487 * as: this will use the collection value as the template context488 * as: global will merge the collection value's properties with _locals_489490- _collection_ Array of objects, the name is derived from the view name itself. 491 For example _video.html_ will have a object _video_ available to it.492493The following are equivalent, and the name of collection value when passed494to the partial will be _movie_ as derived from the name.495496 partial('movie.jade', { collection: movies });497 partial('movie.jade', movies);498 partial('movie', movies);499 // In view: movie.director500501To change the local from _movie_ to _video_ we can use the "as" option:502503 partial('movie', { collection: movies, as: 'video' });504 // In view: video.director505506Also we can make our movie the value of _this_ within our view so that instead507of _movie.director_ we could use _this.director_.508509 partial('movie', { collection: movies, as: this });510 // In view: this.director511512Another alternative is to "explode" the properties of the collection item into513pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:514515 partials('movie', { collection: movies, as: global });516 // In view: director517More docsTj Holowaychukbefore adoptionde81ee7
lines 518–522why, one step back518### app.set(name[, val])519520Apply an application level setting _name_ to _val_, or521get the value of _name_ when _val_ is not present:522Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110
lines 523–525why, one step back523 app.set('views', __dirname + '/views');524 app.set('views');525 // => ...path...More docsTj Holowaychukbefore adoptionde81ee7
lines 526–555why, one step back526527### app.enable(name)528529Enable the given setting _name_:530531 app.enable('some arbitrary setting');532 app.set('some arbitrary setting');533 // => true534535### app.disable(name)536537Disable the given setting _name_:538539 app.disable('some setting');540 app.set('some setting');541 // => false542543### app.configure(env|function[, function])544545Define a callback function for the given _env_ (or all environments) with callback _function_:546547 app.configure(function(){548 // executed for each env549 });550551 app.configure('development', function(){552 // executed for 'development' only553 });554555### app.redirect(name, val)TasksTj Holowaychukbefore adoptiondf7582b
lines 556–566why, one step back556557For use with `res.redirect()` we can map redirects at the application level as shown below:558559 app.redirect('google', 'http://google.com');560561Now in a route we may call:562563 res.redirect('google');564565We may also map dynamic redirects:566Updated docsTj Holowaychukbefore adoptiond691ecb
lines 567–568why, one step back567 app.redirect('comments', function(req, res){568 return '/post/' + req.params.id + '/comments';TasksTj Holowaychukbefore adoptiondf7582b
lines 569–577why, one step back569 });570571So now we may do the following, and the redirect will dynamically adjust to572the context of the request. If we called this route with _GET /post/12_ our573redirect _Location_ would be _/post/12/comments_.574575 app.get('/post/:id', function(req, res){576 res.redirect('comments');577 });Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 578–580why, one step back578579### app.error(function)580More error docsTj Holowaychukbefore adoption6227f5c
lines 581–583why, one step back581Adds an error handler _function_ which will receive the exception as the first parameter as shown below.582Note that we may set several error handlers by making several calls to this method, however the handler583should call _next(err)_ if it does not wish to deal with the exception:Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 584–587why, one step back584585 app.error(function(err, req, res, next){586 res.send(err.message, 500);587 });Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 588–590why, one step back588589### app.helpers(obj)590Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 591–606why, one step back591Registers static view helpers.592593 app.helpers({594 name: function(first, last){ return first + ', ' + last },595 firstName: 'tj',596 lastName: 'holowaychuk'597 });598599Our view could now utilize the _firstName_ and _lastName_ variables,600as well as the _name()_ function exposed.601602 <%= name(firstName, lastName) %>603604### app.dynamicHelpers(obj)605606Registers dynamic view helpers. Dynamic view helpersUpdated docsTj Holowaychukbefore adoptiond691ecb
line 607why, one step back607are simply functions which accept _req_, _res_, and areDocs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 608why, one step back608evaluated against the _Server_ instance before a view is rendered. The _return value_ of this functionAdded app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 609–610why, one step back609becomes the local variable it is associated with.610Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 611why, one step back611 app.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 612why, one step back612 session: function(req, res){Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 613–616why, one step back613 return req.session;614 }615 });616Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 617–619why, one step back617All views would now have _session_ available so that session data can be accessed via _session.name_ etc:618619 <%= session.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 620–633why, one step back620621### app.mounted(fn)622623Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.624625 var app = express.createServer(),626 blog = express.createServer();627 628 blog.mounted(function(parent){629 // parent is app630 // "this" is blog631 });632 633 app.use(blog);Server#listen() docsTj Holowaychukbefore adoptionf3803c4
lines 634–642why, one step back634635### app.listen([port[, host]])636637Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all638connections will be accepted via _INADDR_ANY_.639640 app.listen();641 app.listen(3000);642 app.listen(3000, 'n.n.n.n');Unix domain socket docsTj Holowaychukbefore adoption2fa7907
lines 643–657why, one step back643644The _port_ argument may also be a string representing the path to a unix domain socket:645646 app.listen('/tmp/express.sock');647648Then try it out:649650 $ telnet /tmp/express.sock651 GET / HTTP/1.1652653 HTTP/1.1 200 OK654 Content-Type: text/plain655 Content-Length: 11656 657 Hello World