guide.md
This file
Path
docs/guide.md
655 lines · 19.0 KiB · Markdown
Last changed by
New "home" docsTj Holowaychukbefore adoption1e7a12f
History of this fileTake it
Started guideTj Holowaychukbefore adoption9e3a0c6
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–9why, one step back8npm:9Updated install docsTj Holowaychukbefore adoption193c4a9
line 10why, one step back10 $ npm install connectInstall docsTj Holowaychukbefore adoption63d02f1
lines 11–12why, one step back11 $ npm install express12Updated install docsTj Holowaychukbefore adoption193c4a9
line 13why, one step back13git clone, first update the submodules:Install docsTj Holowaychukbefore adoption63d02f1
line 14why, one step back14Updated install docsTj Holowaychukbefore adoption193c4a9
line 15why, one step back15 $ git submodule update --initInstall docsTj Holowaychukbefore adoption63d02f1
line 16why, one step back16 $ make installUpdated install docsTj Holowaychukbefore adoption193c4a9
line 17why, one step back17 $ make install-supportInstall docsTj Holowaychukbefore adoption63d02f1
line 18why, one step back18Removed annoying padding transitionTj Holowaychukbefore adoption346b2a2
line 19why, one step back19### Creating An ApplicationAdded configuration sectionTj Holowaychukbefore adoption83d2555
lines 20–21why, one step back2021The _express.Server_ now inherits from _http.Server_, howeverMoved config docs upTj Holowaychukbefore adoption6e8413f
lines 22–23why, one step back22follows the same idiom by providing _express.createServer()_ as shown below. This means23that you can utilize Express server's transparently with other libraries.Added configuration sectionTj Holowaychukbefore adoption83d2555
lines 24–32why, one step back2425 var app = require('express').createServer();26 27 app.get('/', function(req, res){28 res.send('hello world');29 });30 31 app.listen(3000);32Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 33–43why, one step back33### Configuration3435Express supports arbitrary environments, such as _production_ and _development_. Developers36can use the _configure()_ method to setup needs required by the current environment. When37_configure()_ is called without an environment name it will be run in _every_ environment 38prior to the environment specific callback.3940In the example below we only _dumpExceptions_, and respond with exception stack traces41in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.4243 app.configure(function(){Updated docsTj Holowaychukbefore adoptioncacada8
lines 44–45why, one step back44 app.use(connect.methodOverride());45 app.use(connect.bodyDecoder());Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 46–48why, one step back46 });47 48 app.configure('development', function(){Updated docsTj Holowaychukbefore adoptioncacada8
line 49why, one step back49 app.use(connect.errorHandler({ dumpExceptions: true, showStack: true }));Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 50–52why, one step back50 });51 52 app.configure('production', function(){Updated docsTj Holowaychukbefore adoptioncacada8
line 53why, one step back53 app.use(connect.errorHandler());Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 54–69why, one step back54 });5556For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:5758 app.configure(function(){59 app.set('views', __dirname + '/views');60 app.set('views');61 // => "... views directory ..."62 63 app.enable('some feature');64 // same as app.set('some feature', true);65 66 app.disable('some feature');67 // same as app.set('some feature', false);68 });69More docsTj Holowaychukbefore adoptionde81ee7
lines 70–74why, one step back70To alter the environment we can set the _CONNECT_ENV_ environment variable,71or more specifically _EXPRESS_ENV_, for example:7273 $ EXPRESS_ENV=production node app.js74Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 75–78why, one step back75### Settings7677Express supports the following settings out of the box:78Updated docsTj Holowaychukbefore adoption4d32762
line 79why, one step back79 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_New "home" docsTj Holowaychukbefore adoption1e7a12f
line 80why, one step back80 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 81–82why, one step back81 * _views_ Root views directory defaulting to **CWD/views**82 * _view engine_ Default view engine name for views rendered without extensionsAdded more setting docsTj Holowaychukbefore adoption38281e6
line 83why, one step back83 * _reload views_ Reloads altered views, by default watches for _mtime_ changes withFixed reload views exampleTj Holowaychukbefore adoption5fcf971
line 84why, one step back84 with a 5 minute interval. Example: _app.set('reload views', 60000);_Moved config docs upTj Holowaychukbefore adoption6e8413f
line 85why, one step back85Started guideTj Holowaychukbefore adoption9e3a0c6
lines 86–89why, one step back86### Routing8788Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.89For example we may want to render a user's account for the path _/user/12_, thisRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 90–91why, one step back90can be done by defining the route below. The values associated to the named placeholders,91are passed as the _third_ argument, which here we name _params_.Started guideTj Holowaychukbefore adoption9e3a0c6
lines 92–101why, one step back9293 app.get('/user/:id', function(req, res, params){94 res.send('user ' + params.id);95 });9697A route is simple a string which is compiled to a _RegExp_ internally. For example98when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:99100 \/user\/([^\/]+)\/?101Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
line 102why, one step back102Regular expression literals may also be passed for complex uses. Since captureUpdated docsTj Holowaychukbefore adoption0111582
line 103why, one step back103groups with literal _RegExp_'s are anonymous we can access them directly from the _params_ array.Started guideTj Holowaychukbefore adoption9e3a0c6
line 104why, one step back104Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
line 105why, one step back105 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res, params){Updated docsTj Holowaychukbefore adoption0111582
line 106why, one step back106 res.send(params);Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
lines 107–118why, one step back107 });108109Curl requests against the previously defined route:110111 $ curl http://dev:3000/user112 [null,null]113 $ curl http://dev:3000/users114 [null,null]115 $ curl http://dev:3000/users/1116 ["1",null]117 $ curl http://dev:3000/users/1..15118 ["1","15"]Started guideTj Holowaychukbefore adoption9e3a0c6
lines 119–149why, one step back119120Below are some route examples, and the associated paths that they121may consume:122123 "/user/:id"124 /user/12125126 "/users/:id?"127 /users/5128 /users129130 "/files/*"131 /files/jquery.js132 /files/javascripts/jquery.js133134 "/file/*.*"135 /files/jquery.js136 /files/javascripts/jquery.js137 138 "/user/:id/:operation?"139 /user/1140 /user/1/edit141 142 "/products.:format"143 /products.json144 /products.xml145146 "/products.:format?"147 /products.json148 /products.xml149 /productsRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 150–165why, one step back150151### Passing Route Control152153We may pass control to the next _matching_ route, by calling the _fourth_ parameter,154the _next()_ function. When a match cannot be made, control is passed back to Connect.155156 app.get('/users/:id?', function(req, res, params){157 if (params.id) {158 // do something159 } else {160 next();161 }162 });163 164 app.get('/users', function(req, res, params){165 // do something elseAdded configuration sectionTj Holowaychukbefore adoption83d2555
lines 166–180why, one step back166 });167168### Middleware169170The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be171passed to _express.createServer()_ as you would with a regular Connect server. For example:172173 var connect = require('connect'),174 express = require('express');175176 var app = express.createServer(177 connect.logger(),178 connect.bodyDecoder()179 );180Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 181–182why, one step back181Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:182Updated docsTj Holowaychukbefore adoptioncacada8
line 183why, one step back183 app.use(connect.logger({ format: ':method :uri' }));Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 184–229why, one step back184185### Error Handling186187Express provides the _app.error()_ method which receives exceptions thrown within a route,188or passed to _next(err)_. Below is an example which serves different pages based on our189ad-hoc _NotFound_ exception:190191 function NotFound(msg){192 this.name = 'NotFound';193 Error.call(this, msg);194 Error.captureStackTrace(this, arguments.callee);195 }196197 sys.inherits(NotFound, Error);198199 app.get('/404', function(req, res){200 throw new NotFound;201 });202203 app.get('/500', function(req, res){204 throw new Error('keyboard cat!');205 });206207We can call _app.error()_ several times as shown below.208Here we check for an instanceof _NotFound_ and show the209404 page, or we pass on to the next error handler.210211 app.error(function(err, req, res, next){212 if (err instanceof NotFound) {213 res.render('404.jade');214 } else {215 next(err);216 }217 });218219Here we assume all errors as 500 for the simplicity of220this demo, however you can choose whatever you like221222 app.error(function(err, req, res){223 res.render('500.jade', {224 locals: {225 error: err226 } 227 });228 });229More error handling docsTj Holowaychukbefore adoptioncea401c
lines 230–233why, one step back230Our apps could also utilize the Connect _errorHandler_ middleware231to report on exceptions. For example if we wish to output exceptions 232in "development" mode to _stderr_ we can use:233Updated docsTj Holowaychukbefore adoptioncacada8
line 234why, one step back234 app.use(connect.errorHandler({ dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 235–238why, one step back235236Also during development we may want fancy html pages to show exceptions237that are passed or thrown, so we can set _showStack_ to true:238Updated docsTj Holowaychukbefore adoptioncacada8
line 239why, one step back239 app.use(connect.errorHandler({ showStack: true, dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 240–243why, one step back240241The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_242is present, which is useful for developing apps that rely heavily on client-side JavaScript.243Added more view docsTj Holowaychukbefore adoption2f96506
lines 244–261why, one step back244### View Rendering245246View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name247of the module that will be required. For example the view _layout.ejs_ will248tell the view system to _require('ejs')_, the module being loaded must (currently)249export the method _exports.render(str, options)_ to comply with Express, however 250with will likely be extensible in the future.251252Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,253and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 254the _body_ local variable in _layout.haml_.255256 app.get('/', function(req, res){257 res.render('index.haml', {258 locals: { title: 'My Site' }259 });260 });261Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
lines 262–279why, one step back262The new _view engine_ setting allows us to specify our default template engine,263so for example when using [Jade](http://github.com/visionmedia/jade) we could set:264265 app.set('view engine', 'jade');266267Allowing us to render with:268269 res.render('index');270271vs:272273 res.render('index.jade');274275When _view engine_ is set, extensions are entirely optional, however we can still276mix and match template engines:277278 res.render('another-page.ejs');279Added more view docsTj Holowaychukbefore adoption2f96506
lines 280–297why, one step back280### View Partials281282The Express view system has built-in support for partials and collections, which are283sort of "mini" views representing a document fragment. For example rather than iterating284in a view to display comments, we would use a partial with collection support:285286 partial('comment.haml', { collection: comments });287288To make things even less verbose we can assume the extension as _.haml_ when omitted,289however if we wished we could use an ejs partial, within a haml view for example.290291 partial('comment', { collection: comments });292293And once again even further, when rendering a collection we can simply pass294an array, if no other options are desired:295296 partial('comments', comments);297Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701
lines 298–304why, one step back298When using the partial collection support a few "magic" variables are provided299for free:300301 * _firstInCollection_ True if this is the first object302 * _indexInCollection_ Index of the object in the collection303 * _lastInCollection _ True if this is the last object304Added more view docsTj Holowaychukbefore adoption2f96506
lines 305–312why, one step back305### Template Engines306307Below are a few template engines commonly used with Express:308309 * [Jade](http://github.com/visionmedia/jade) haml.js successor310 * [Haml](http://github.com/visionmedia/haml.js) indented templates311 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript312More docsTj Holowaychukbefore adoptionde81ee7
line 313why, one step back313### req.header(key[, defaultValue])More docsTj Holowaychukbefore adoptiondfecbe5
lines 314–320why, one step back314315Get the case-insensitive request header _key_, with optional _defaultValue_:316317 req.header('Host');318 req.header('host');319 req.header('Accept', '*/*');320More docsTj Holowaychukbefore adoptionde81ee7
line 321why, one step back321### req.accepts(type)More docsTj Holowaychukbefore adoptiondfecbe5
lines 322–344why, one step back322323Check if the _Accept_ header is present, and includes the given _type_.324325When the _Accept_ header is not present _true_ is returned. Otherwise326the given _type_ is matched by an exact match, and then subtypes. You327may pass the subtype such as "html" which is then converted internally328to "text/html" using the mime lookup table.329330 // Accept: text/html331 req.accepts('html');332 // => true333334 // Accept: text/*; application/json335 req.accepts('html');336 req.accepts('text/html');337 req.accepts('text/plain');338 req.accepts('application/json');339 // => true340341 req.accepts('image/png');342 req.accepts('png');343 // => false344More docsTj Holowaychukbefore adoptionde81ee7
line 345why, one step back345### req.param(name)More docsTj Holowaychukbefore adoptiondfecbe5
lines 346–356why, one step back346347Return the value of param _name_ when present.348349 - Checks route placeholders, ex: /user/:id350 - Checks query string params, ex: ?id=12351 - Checks urlencoded body params, ex: id=12352353To utilize urlencoded request bodies, _req.body_354should be an object. This can be done by using355the _connect.bodyDecoder_ middleware.356More docsTj Holowaychukbefore adoptionde81ee7
line 357why, one step back357### req.flash(type[, msg])More docsTj Holowaychukbefore adoptiondfecbe5
lines 358–374why, one step back358359Queue flash _msg_ of the given _type_.360361 req.flash('info', 'email sent');362 req.flash('error', 'email delivery failed');363 req.flash('info', 'email re-sent');364 // => 2365366 req.flash('info');367 // => ['email sent', 'email re-sent']368369 req.flash('info');370 // => []371372 req.flash();373 // => { error: ['email delivery failed'], info: [] }374More docsTj Holowaychukbefore adoptionde81ee7
line 375why, one step back375### req.isXMLHttpRequestMore docsTj Holowaychukbefore adoptiondfecbe5
lines 376–382why, one step back376377Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header378to see if it was issued by an _XMLHttpRequest_:379380 req.xhr381 req.isXMLHttpRequest382More docsTj Holowaychukbefore adoptionde81ee7
line 383why, one step back383### res.header(key[, val])More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 384–395why, one step back384385Get or set the response header _key_.386387 res.header('Content-Length');388 // => undefined389390 res.header('Content-Length', 123);391 // => 123392393 res.header('Content-Length');394 // => 123395More docsTj Holowaychukbefore adoptionde81ee7
line 396why, one step back396### res.contentType(type)More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 397–403why, one step back397398Sets the _Content-Type_ response header to the given _type_.399400 var filename = 'path/to/image.png';401 res.contentType(filename);402 // res.headers['Content-Type'] is now "image/png"403More docsTj Holowaychukbefore adoptionde81ee7
line 404why, one step back404### res.attachment([filename])Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
lines 405–409why, one step back405406Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.407408 res.attachment('path/to/my/image.png');409More docsTj Holowaychukbefore adoptionde81ee7
line 410why, one step back410### res.sendfile(path)Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 411–415why, one step back411412Used by `res.download()` to transfer an arbitrary file. 413414 res.sendfile('path/to/my.file');415Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1
lines 416–419why, one step back416This is _not_ a substitution for Connect's _staticProvider_ middleware, it does not417support HTTP caching, and does not perform any security checks. This method is utilized418by _res.download()_ to transfer static files, and allows you do to so from outside of419the public directory, so suitable security checks should be applied.Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
line 420why, one step back420More docsTj Holowaychukbefore adoptionde81ee7
line 421why, one step back421### res.download(file[, filename])Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 422–432why, one step back422423Transfer the given _file_ as an attachment with optional alternative _filename_.424425 res.download('path/to/image.png');426 res.download('path/to/image.png', 'foo.png');427428This is equivalent to:429430 res.attachment(file);431 res.sendfile(file);432More docsTj Holowaychukbefore adoptionde81ee7
line 433why, one step back433### res.send(body|status[, headers|status[, status]])Docs for res.send()Tj Holowaychukbefore adoption5a48248
lines 434–449why, one step back434435The `res.send()` method is a high level response utility allowing you to pass436objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status437code based responses. The following are all valid uses:438439 res.send(new Buffer('wahoo'));440 res.send({ some: 'json' });441 res.send('<p>some html</p>');442 res.send('Sorry, cant find that', 404);443 res.send('text', { 'Content-Type': 'text/plain' }, 201);444 res.send(404);445446By default the _Content-Type_ response header is set, however if explicitly447assigned through `res.send()` or previously with `res.header()` or `res.contentType()`448it will not be set again.449More docsTj Holowaychukbefore adoptionde81ee7
line 450why, one step back450### res.redirect(url[, status])Added configuration sectionTj Holowaychukbefore adoption83d2555
line 451why, one step back451More docsTj Holowaychukbefore adoptionbedff32
line 452why, one step back452Redirect to the given _url_ with a default response _status_ of 302.Configuration docsTj Holowaychukbefore adoptioncb04364
line 453why, one step back453More docsTj Holowaychukbefore adoptionbedff32
lines 454–463why, one step back454 res.redirect('/', 301);455 res.redirect('/account');456 res.redirect('http://google.com');457 res.redirect('home');458 res.redirect('back');459460Express supports "redirect mapping", which by default provides _home_, and _back_.461The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes462the "home" setting and defaults to "/".463More view docsTj Holowaychukbefore adoption1c8ff48
lines 464–474why, one step back464### res.render(view[, options[, fn]])465466Render _view_ with the given _options_ and optional callback _fn_.467When a callback function is given a response will _not_ be made468automatically, however otherwise a response of _200_ and _text/html_ is given.469470 Most engines accept one or more of the following options,471 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:472473 - _context|scope_ Template evaluation context (_this_)474 - _locals_ Object containing local variablesCleaning up view docsTj Holowaychukbefore adoption25c8883
line 475why, one step back475 - _cache_ Cache intermediate JavaScript in memory (the default in _production_ mode)More view docsTj Holowaychukbefore adoption1c8ff48
lines 476–477why, one step back476 - _debug_ Output debugging information477In depth partial docsTj Holowaychukbefore adoption793943f
lines 478–515why, one step back478### res.partial(view[, options])479480Render _view_ partial with the given _options_. This method is always available481to the view as a local variable.482483- _as_ Variable name for each _collection_ value, defaults to the view name.484 * as: 'something' will add the _something_ local variable485 * as: this will use the collection value as the template context486 * as: global will merge the collection value's properties with _locals_487488- _collection_ Array of objects, the name is derived from the view name itself. 489 For example _video.html_ will have a object _video_ available to it.490491The following are equivalent, and the name of collection value when passed492to the partial will be _movie_ as derived from the name.493494 partial('movie.jade', { collection: movies });495 partial('movie.jade', movies);496 partial('movie', movies);497 // In view: movie.director498499To change the local from _movie_ to _video_ we can use the "as" option:500501 partial('movie', { collection: movies, as: 'video' });502 // In view: video.director503504Also we can make our movie the value of _this_ within our view so that instead505of _movie.director_ we could use _this.director_.506507 partial('movie', { collection: movies, as: this });508 // In view: this.director509510Another alternative is to "explode" the properties of the collection item into511pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:512513 partials('movie', { collection: movies, as: global });514 // In view: director515More docsTj Holowaychukbefore adoptionde81ee7
lines 516–553why, one step back516### app.set(name[, val])517518Apply an application level setting _name_ to _val_, or519get the value of _name_ when _val_ is not present:520521 app.set('reload views', 200);522 app.set('reload views');523 // => 200524525### app.enable(name)526527Enable the given setting _name_:528529 app.enable('some arbitrary setting');530 app.set('some arbitrary setting');531 // => true532533### app.disable(name)534535Disable the given setting _name_:536537 app.disable('some setting');538 app.set('some setting');539 // => false540541### app.configure(env|function[, function])542543Define a callback function for the given _env_ (or all environments) with callback _function_:544545 app.configure(function(){546 // executed for each env547 });548549 app.configure('development', function(){550 // executed for 'development' only551 });552553### app.redirect(name, val)More docsTj Holowaychukbefore adoptionbedff32
lines 554–575why, one step back554555For use with `res.redirect()` we can map redirects at the application level as shown below:556557 app.redirect('google', 'http://google.com');558559Now in a route we may call:560561 res.redirect('google');562563We may also map dynamic redirects:564565 app.redirect('comments', function(req, res, params){566 return '/post/' + params.id + '/comments';567 });568569So now we may do the following, and the redirect will dynamically adjust to570the context of the request. If we called this route with _GET /post/12_ our571redirect _Location_ would be _/post/12/comments_.572573 app.get('/post/:id', function(req, res){574 res.redirect('comments');575 });Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 576–578why, one step back576577### app.error(function)578More error docsTj Holowaychukbefore adoption6227f5c
lines 579–581why, one step back579Adds an error handler _function_ which will receive the exception as the first parameter as shown below.580Note that we may set several error handlers by making several calls to this method, however the handler581should call _next(err)_ if it does not wish to deal with the exception:Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 582–585why, one step back582583 app.error(function(err, req, res, next){584 res.send(err.message, 500);585 });Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 586–588why, one step back586587### app.helpers(obj)588Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 589–604why, one step back589Registers static view helpers.590591 app.helpers({592 name: function(first, last){ return first + ', ' + last },593 firstName: 'tj',594 lastName: 'holowaychuk'595 });596597Our view could now utilize the _firstName_ and _lastName_ variables,598as well as the _name()_ function exposed.599600 <%= name(firstName, lastName) %>601602### app.dynamicHelpers(obj)603604Registers dynamic view helpers. Dynamic view helpersAdded app.helpers() docsTj Holowaychukbefore adoption7eb088b
line 605why, one step back605are simply functions which accept _req_, _res_, and _params_, and areDocs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 606why, one step back606evaluated against the _Server_ instance before a view is rendered. The _return value_ of this functionAdded app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 607–608why, one step back607becomes the local variable it is associated with.608Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 609why, one step back609 app.dynamicHelpers({Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 610–614why, one step back610 session: function(req, res, params){611 return req.session;612 }613 });614Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 615–617why, one step back615All views would now have _session_ available so that session data can be accessed via _session.name_ etc:616617 <%= session.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 618–631why, one step back618619### app.mounted(fn)620621Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.622623 var app = express.createServer(),624 blog = express.createServer();625 626 blog.mounted(function(parent){627 // parent is app628 // "this" is blog629 });630 631 app.use(blog);Server#listen() docsTj Holowaychukbefore adoptionf3803c4
lines 632–640why, one step back632633### app.listen([port[, host]])634635Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all636connections will be accepted via _INADDR_ANY_.637638 app.listen();639 app.listen(3000);640 app.listen(3000, 'n.n.n.n');Unix domain socket docsTj Holowaychukbefore adoption2fa7907
lines 641–655why, one step back641642The _port_ argument may also be a string representing the path to a unix domain socket:643644 app.listen('/tmp/express.sock');645646Then try it out:647648 $ telnet /tmp/express.sock649 GET / HTTP/1.1650651 HTTP/1.1 200 OK652 Content-Type: text/plain653 Content-Length: 11654 655 Hello World