Skip to content
Myr

Added new dox API docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by TJ Holowaychuk · committed by TJ Holowaychuk · parent 856f3b3 · Browse files · 8 files+655 added−90 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+655 added−90 removed

  • other:+655 added−90 removed

8 files+655 added−90 removed

added:docs/application.md+170 added
12# app34 Application prototype.56# app.use()78 Proxy `connect#use()` to apply settings to9 mounted applications.1011# app.engine()1213 Register the given template engine callback `fn`14 as `ext`. For example if you wanted to map the EJS15 template engine to ".html" files, rather than ".ejs" files,16 you could do the following.17 18 app.engine('html', require('ejs').renderFile);19 20 In this case EJS provides a `.renderFile()` method with21 the same signature that Express expects: `(path, options, callback)`.22 23 Some template engines do not follow this convention, the24 [Consolidate.js](https://github.com/visionmedia/consolidate.js)25 library was created to map all of node's popular template26 engines to follow this convention, thus allowing them to27 work seemlessly within Express.2829# app.param()3031 Map the given param placeholder `name`(s) to the given callback(s).32 33 Parameter mapping is used to provide pre-conditions to routes34 which use normalized placeholders. For example a _:user_id_ parameter35 could automatically load a user's information from the database without36 any additional code,37 38 The callback uses the samesignature as middleware, the only differencing39 being that the value of the placeholder is passed, in this case the _id_40 of the user. Once the `next()` function is invoked, just like middleware41 it will continue on to execute the route, or subsequent parameter functions.42 43 app.param('user_id', function(req, res, next, id){44 User.find(id, function(err, user){45 if (err) {46 next(err);47 } else if (user) {48 req.user = user;49 next();50 } else {51 next(new Error('failed to load user'));52 }53 });54 });5556# app.set()5758 Assign `setting` to `val`, or return `setting`'s value.59 60 app.set('foo', 'bar');61 app.get('foo');62 // => "bar"63 64 Mounted servers inherit their parent server's settings.6566# app.enabled()6768 Check if `setting` is enabled (truthy).69 70 app.enabled('foo')71 // => false72 73 app.enable('foo')74 app.enabled('foo')75 // => true7677# app.disabled()7879 Check if `setting` is disabled.80 81 app.disabled('foo')82 // => true83 84 app.enable('foo')85 app.disabled('foo')86 // => false8788# app.enable()8990 Enable `setting`.9192# app.disable()9394 Disable `setting`.9596# app.configure()9798 Configure callback for zero or more envs,99 when no `env` is specified that callback will100 be invoked for all environments. Any combination101 can be used multiple times, in any order desired.102 103 ## Examples104 105 app.configure(function(){106 // executed for all envs107 });108 109 app.configure('stage', function(){110 // executed staging env111 });112 113 app.configure('stage', 'production', function(){114 // executed for stage and production115 });116 117 ## Note118 119 These callbacks are invoked immediately, and120 are effectively sugar for the following.121 122 var env = process.env.NODE_ENV || 'development';123 124 switch (env) {125 case 'development':126 ...127 break;128 case 'stage':129 ...130 break;131 case 'production':132 ...133 break;134 }135136# app.all()137138 Special-cased "all" method, applying the given route `path`,139 middleware, and callback to _every_ HTTP method.140141# app.render()142143 Render the given view `name` name with `options`144 and a callback accepting an error and the145 rendered template string.146 147 ## Example148 149 app.render('email', { name: 'Tobi' }, function(err, html){150 // ...151 })152153# app.listen()154155 Listen for connections.156 157 A node `http.Server` is returned, with this158 application (which is a `Function`) as its159 callback. If you wish to create both an HTTP160 and HTTPS server you may do so with the "http"161 and "https" modules as shown here.162 163 var http = require('http')164 , https = require('https')165 , express = require('express')166 , app = express();167 168 http.createServer(app).listen(80);169 http.createServer({ ... }, app).listen(443);170
added:docs/request.md+117 added
12# req34 Request prototype.56# req.get()78 Return request header.9 10 The `Referrer` header field is special-cased,11 both `Referrer` and `Referer` will yield are12 interchangeable.13 14 ## Examples15 16 req.get('Content-Type');17 // => "text/plain"18 19 req.get('content-type');20 // => "text/plain"21 22 req.get('Something');23 // => undefined2425# req.accepts()2627 Check if the given `type(s)` is acceptable, returning28 the best match when true, otherwise `undefined`, in which29 case you should respond with 406 "Not Acceptable".30 31 The `type` value may be a single mime type string32 such as "application/json", the extension name33 such as "json", a comma-delimted list such as "json, html, text/plain",34 or an array `["json", "html", "text/plain"]`. When a list35 or array is given the _best_ match, if any is returned.36 37 ## Examples38 39 // Accept: text/html40 req.accepts('html');41 // => "html"42 43 // Accept: text/*, application/json44 req.accepts('html');45 // => "html"46 req.accepts('text/html');47 // => "text/html"48 req.accepts('json, text');49 // => "json"50 req.accepts('application/json');51 // => "application/json"52 53 // Accept: text/*, application/json54 req.accepts('image/png');55 req.accepts('png');56 // => undefined57 58 // Accept: text/*;q=.5, application/json59 req.accepts(['html', 'json']);60 req.accepts('html, json');61 // => "json"6263# req.acceptsCharset()6465 Check if the given `charset` is acceptable,66 otherwise you should respond with 406 "Not Acceptable".6768# req.acceptsLanguage()6970 Check if the given `lang` is acceptable,71 otherwise you should respond with 406 "Not Acceptable".7273# req.param()7475 Return the value of param `name` when present or `defaultValue`.76 77 - Checks body params, ex: id=12, {"id":12}78 - Checks route placeholders, ex: _/user/:id_79 - Checks query string params, ex: ?id=1280 81 To utilize request bodies, `req.body`82 should be an object. This can be done by using83 the `connect.bodyParser()` middleware.8485# req.is()8687 Check if the incoming request contains the "Content-Type" 88 header field, and it contains the give mime `type`.89 90 ## Examples91 92 // With Content-Type: text/html; charset=utf-893 req.is('html');94 req.is('text/html');95 req.is('text/*');96 // => true97 98 // When Content-Type is application/json99 req.is('json');100 req.is('application/json');101 req.is('application/*');102 // => true103 104 req.is('html');105 // => false106 107 Now within our route callbacks, we can use to to assert content types108 such as "image/jpeg", "image/png", etc.109 110 app.post('/image/upload', function(req, res, next){111 if (req.is('image/*')) {112 // do something113 } else {114 next();115 }116 });117
added:docs/response.md+212 added
12# res34 Response prototype.56# res.status()78 Set status `code`.910# res.send()1112 Send a response.13 14 ## Examples15 16 res.send(new Buffer('wahoo'));17 res.send({ some: 'json' });18 res.send('<p>some html</p>');19 res.send(404, 'Sorry, cant find that');20 res.send(404);2122# res.json()2324 Send JSON response.25 26 ## Examples27 28 res.json(null);29 res.json({ user: 'tj' });30 res.json(500, 'oh noes!');31 res.json(404, 'I dont have that');3233# res.sendfile()3435 Transfer the file at the given `path`.36 37 Automatically sets the _Content-Type_ response header field.38 The callback `fn(err)` is invoked when the transfer is complete39 or when an error occurs. Be sure to check `res.sentHeader`40 if you wish to attempt responding, as the header and some data41 may have already been transferred.42 43 ## Options44 45 - `maxAge` defaulting to 046 - `root` root directory for relative filenames47 48 ## Examples49 50 The following example illustrates how `res.sendfile()` may51 be used as an alternative for the `static()` middleware for52 dynamic situations. The code backing `res.sendfile()` is actually53 the same code, so HTTP cache support etc is identical.54 55 app.get('/user/:uid/photos/:file', function(req, res){56 var uid = req.params.uid57 , file = req.params.file;58 59 req.user.mayViewFilesFrom(uid, function(yes){60 if (yes) {61 res.sendfile('/uploads/' + uid + '/' + file);62 } else {63 res.send(403, 'Sorry! you cant see that.');64 }65 });66 });6768# res.download()6970 Transfer the file at the given `path` as an attachment.71 72 Optionally providing an alternate attachment `filename`,73 and optional callback `fn(err)`. The callback is invoked74 when the data transfer is complete, or when an error has75 ocurred. Be sure to check `res.headerSent` if you plan to respond.7677# res.format()7879 Respond to the Acceptable formats using an `obj`80 of mime-type callbacks.81 82 This method uses `req.accepted`, an array of83 acceptable types ordered by their quality values.84 When "Accept" is not present the _first_ callback85 is invoked, otherwise the first match is used. When86 no match is performed the server responds with87 406 "Not Acceptable".88 89 Content-Type is set for you, however if you choose90 you may alter this within the callback using `res.type()`91 or `res.set('Content-Type', ...)`.92 93 res.format({94 'text/plain': function(){95 res.send('hey');96 },97 98 'text/html': function(){99 res.send('<p>hey</p>');100 },101 102 'appliation/json': function(){103 res.send({ message: 'hey' });104 }105 });106 107 In addition to canonicalized MIME types you may108 ## also use extnames mapped to these types109 110 res.format({111 text: function(){112 res.send('hey');113 },114 115 html: function(){116 res.send('<p>hey</p>');117 },118 119 json: function(){120 res.send({ message: 'hey' });121 }122 });123124# res.attachment()125126 Set _Content-Disposition_ header to _attachment_ with optional `filename`.127128# res.set()129130 Set header `field` to `val`, or pass131 an object of of header fields.132 133 ## Examples134 135 res.set('Accept', 'application/json');136 res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });137138# res.get()139140 Get value for header `field`.141142# res.clearCookie()143144 Clear cookie `name`.145146# res.signedCookie()147148 Set a signed cookie with the given `name` and `val`.149 See `res.cookie()` for details.150151# res.cookie()152153 Set cookie `name` to `val`, with the given `options`.154 155 ## Options156 157 - `maxAge` max-age in milliseconds, converted to `expires`158 - `path` defaults to "/"159 160 ## Examples161 162 // "Remember Me" for 15 minutes163 res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });164 165 // save as above166 res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })167168# res.redirect()169170 Redirect to the given `url` with optional response `status`171 defaulting to 302.172 173 The given `url` can also be the name of a mapped url, for174 example by default express supports "back" which redirects175 to the _Referrer_ or _Referer_ headers or "/".176 177 ## Examples178 179 res.redirect('/foo/bar');180 res.redirect('http://example.com');181 res.redirect(301, 'http://example.com');182 res.redirect('../login'); // /blog/post/1 -> /blog/login183 184 ## Mounting185 186 When an application is mounted, and `res.redirect()`187 is given a path that does _not_ lead with "/". For 188 example suppose a "blog" app is mounted at "/blog",189 the following redirect would result in "/blog/login":190 191 res.redirect('login');192 193 While the leading slash would result in a redirect to "/login":194 195 res.redirect('/login');196197# res.render()198199 Render `view` with the given `options` and optional callback `fn`.200 When a callback function is given a response will _not_ be made201 automatically, otherwise a response of _200_ and _text/html_ is given.202 203 ## Options204 205 - `status` Response status code (`res.statusCode`)206 - `charset` Set the charset (`res.charset`)207 208 ## Reserved locals209 210 - `cache` boolean hinting to the engine it should cache211 - `filename` filename of the view being rendered212
modified:lib/application.js+100 added-86 removed
122 unmodified lines
123 });124};125126/**127 * Remove routes matching the given `path`.128 *129 * @param {Route} path130 * @return {Boolean}131 * @api public132 */133134app.remove = function(path){135 return this._router.lookup('all', path).remove();136};137138/**139 * Lookup routes defined with a path140 * equivalent to `path`.141 *142 * @param {String} path143 * @return {Array}144 * @api public145 */146147app.lookup = function(path){148 return this._router.lookup('all', path);149};150151/**127 * Proxy `connect#use()` to apply settings to128 * mounted applications.129 *130 * @param {String|Function|Server} route
35 unmodified lines
166};167168/**169 * Register the given template engine callback `fn`195 * as `ext`. For example we may wish to map ".html"196 * files to ejs rather than using the ".ejs" extension.170 * as `ext`. For example if you wanted to map the EJS171 * template engine to ".html" files, rather than ".ejs" files,172 * you could do the following.173 *198 * app.engine('.html', require('ejs').render);174 * app.engine('html', require('ejs').renderFile);175 *200 * or176 * In this case EJS provides a `.renderFile()` method with177 * the same signature that Express expects: `(path, options, callback)`.178 *202 * app.engine('html', require('ejs').render);179 * Some template engines do not follow this convention, the180 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)181 * library was created to map all of node's popular template182 * engines to follow this convention, thus allowing them to183 * work seemlessly within Express.184 *185 * @param {String} ext186 * @param {Function} fn187 * @return {app} for chaining
9 unmodified lines
197198/**199 * Map the given param placeholder `name`(s) to the given callback(s).200 *220 * Param mapping is used to provide pre-conditions to routes221 * which us normalized placeholders. This callback has the same222 * signature as regular middleware, for example below when ":userId"223 * is used this function will be invoked in an attempt to load the user.201 * Parameter mapping is used to provide pre-conditions to routes202 * which use normalized placeholders. For example a _:user_id_ parameter203 * could automatically load a user's information from the database without204 * any additional code,205 *206 * The callback uses the samesignature as middleware, the only differencing207 * being that the value of the placeholder is passed, in this case the _id_208 * of the user. Once the `next()` function is invoked, just like middleware209 * it will continue on to execute the route, or subsequent parameter functions.210 *225 * app.param('userId', function(req, res, next, id){211 * app.param('user_id', function(req, res, next, id){212 * User.find(id, function(err, user){213 * if (err) {214 * next(err);215 * } else if (user) {
4 unmodified lines
220 * }221 * });222 * });223 *238 * Passing a single function allows you to map logic239 * to the values passed to `app.param()`, for example240 * this is useful to provide coercion support in a concise manner.241 *242 * The following example maps regular expressions to param values243 * ensuring that they match, otherwise passing control to the next244 * route:245 *246 * app.param(function(name, regexp){247 * if (regexp instanceof RegExp) {248 * return function(req, res, next, val){249 * var captures;250 * if (captures = regexp.exec(String(val))) {251 * req.params[name] = captures;252 * next();253 * } else {254 * next('route');255 * }256 * }257 * }258 * });259 *260 * We can now use it as shown below, where "/commit/:commit" expects261 * that the value for ":commit" is at 5 or more digits. The capture262 * groups are then available as `req.params.commit` as we defined263 * in the function above.264 *265 * app.param('commit', /^\d{5,}$/);266 *267 * For more of this useful functionality take a look268 * at [express-params](http://github.com/visionmedia/express-params).269 *270 * @param {String|Array|Function} name224 * @param {String|Array} name225 * @param {Function} fn226 * @return {app} for chaining227 * @api public228 */
24 unmodified lines
253};254255/**256 * Assign `setting` to `val`, or return `setting`'s value.257 *258 * app.set('foo', 'bar');259 * app.get('foo');260 * // => "bar"261 *262 * Mounted servers inherit their parent server's settings.263 *264 * @param {String} setting265 * @param {String} val307 * @return {Server|Mixed} for chaining, or the setting value266 * @return {Server} for chaining267 * @api public268 */269270app.set = function(setting, val){
13 unmodified lines
284 * Return the app's absolute pathname285 * based on the parent(s) that have286 * mounted it.287 *288 * For example if the application was289 * mounted as "/admin", which itself290 * was mounted as "/blog" then the291 * return value would be "/blog/admin".292 *293 * @return {String}294 * @api private295 */296
3 unmodified lines
300 : '';301};302303/**340 * Check if `setting` is enabled.304 * Check if `setting` is enabled (truthy).305 *306 * app.enabled('foo')307 * // => false308 *309 * app.enable('foo')310 * app.enabled('foo')311 * // => true312 *313 * @param {String} setting314 * @return {Boolean}315 * @api public316 */
4 unmodified lines
321322/**323 * Check if `setting` is disabled.324 *325 * app.disabled('foo')326 * // => true327 *328 * app.enable('foo')329 * app.disabled('foo')330 * // => false331 *332 * @param {String} setting333 * @return {Boolean}334 * @api public335 */
27 unmodified lines
363};364365/**366 * Configure callback for zero or more envs,389 * when no env is specified that callback will367 * when no `env` is specified that callback will368 * be invoked for all environments. Any combination369 * can be used multiple times, in any order desired.370 *371 * Examples:
9 unmodified lines
381 * app.configure('stage', 'production', function(){382 * // executed for stage and production383 * });384 *385 * Note:386 *387 * These callbacks are invoked immediately, and388 * are effectively sugar for the following.389 *390 * var env = process.env.NODE_ENV || 'development';391 *392 * switch (env) {393 * case 'development':394 * ...395 * break;396 * case 'stage':397 * ...398 * break;399 * case 'production':400 * ...401 * break;402 * }403 *404 * @param {String} env...405 * @param {Function} fn406 * @return {app} for chaining407 * @api public
8 unmodified lines
416 return this;417};418419/**423 * Listen for connections.424 *425 * This method takes the same arguments426 * as node's `http.Server#listen()`. 427 *428 * @return {http.Server}429 * @api public430 */431432app.listen = function(){433 var server = http.createServer(this);434 return server.listen.apply(server, arguments);435};436437/**420 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.421 */422423methods.forEach(function(method){
32 unmodified lines
456 * Render the given view `name` name with `options`457 * and a callback accepting an error and the458 * rendered template string.459 *460 * Example:461 *462 * app.render('email', { name: 'Tobi' }, function(err, html){463 * // ...464 * })465 *466 * @param {String} name467 * @param {String|Function} options or fn468 * @param {Function} fn469 * @api public
50 unmodified lines
520 } catch (err) {521 fn(err);522 }523};524525/**526 * Listen for connections.527 *528 * A node `http.Server` is returned, with this529 * application (which is a `Function`) as its530 * callback. If you wish to create both an HTTP531 * and HTTPS server you may do so with the "http"532 * and "https" modules as shown here.533 *534 * var http = require('http')535 * , https = require('https')536 * , express = require('express')537 * , app = express();538 *539 * http.createServer(app).listen(80);540 * http.createServer({ ... }, app).listen(443);541 *542 * @return {http.Server}543 * @api public544 */545546app.listen = function(){547 var server = http.createServer(this);548 return server.listen.apply(server, arguments);549};
modified:lib/request.js+1 added-1 removed
364 unmodified lines
365 .reverse();366});367368/**369 * Short-hand for `require('url').parse(req.url).pathname`.369 * Short-hand for `url.parse(req.url).pathname`.370 *371 * @return {String}372 * @api public373 */
42 unmodified lines
modified:lib/response.js+24 added-2 removed
169 unmodified lines
170 *171 * - `maxAge` defaulting to 0172 * - `root` root directory for relative filenames173 *174 * Examples:175 *176 * The following example illustrates how `res.sendfile()` may177 * be used as an alternative for the `static()` middleware for178 * dynamic situations. The code backing `res.sendfile()` is actually179 * the same code, so HTTP cache support etc is identical.180 *181 * app.get('/user/:uid/photos/:file', function(req, res){182 * var uid = req.params.uid183 * , file = req.params.file;184 * 185 * req.user.mayViewFilesFrom(uid, function(yes){186 * if (yes) {187 * res.sendfile('/uploads/' + uid + '/' + file);188 * } else {189 * res.send(403, 'Sorry! you cant see that.');190 * }191 * });192 * });193 *194 * @param {String} path195 * @param {Object|Function} options or fn196 * @param {Function} fn197 * @api public
49 unmodified lines
247 * and optional callback `fn(err)`. The callback is invoked248 * when the data transfer is complete, or when an error has249 * ocurred. Be sure to check `res.headerSent` if you plan to respond.250 *251 * This method uses `res.attachment()` and `res.sendfile()`.252 *253 * @param {String} path254 * @param {String|Function} filename or fn255 * @param {Function} fn256 * @api public
295 unmodified lines
552 }553554 // Support text/{plain,html} by default555 this.format({534 'text/plain': function(){556 text: function(){557 body = statusCodes[status] + '. Redirecting to ' + url;558 },559538 'text/html': function(){560 html: function(){561 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';562 }563 })564
76 unmodified lines
added:support/docs+21 added
1#!/usr/bin/env node23var buf = '';4process.stdin.setEncoding('utf8');5process.stdin.on('data', function(chunk){6 buf += chunk;7}).on('end', function(){8 var comments = JSON.parse(buf);9 comments.forEach(function(comment){10 if (comment.ignore) return;11 if (comment.isPrivate) return;12 if (!comment.ctx) return;13 if (!comment.description.full.indexOf('Module dep')) return;14 var ctx = comment.ctx;15 console.log();16 console.log('# %s', ctx.string);17 console.log();18 console.log(comment.description.full.trim().replace(/^/gm, ' '));19 });20 console.log();21}).resume();
modified:Makefile+10 added-1 removed
12REPORTER = dot34docs: docs/application.md docs/request.md docs/response.md56docs/%.md: lib/%.js7 @mkdir -p docs8 dox --raw < $< | ./support/docs > $@910test:11 @NODE_ENV=test ./node_modules/.bin/mocha \12 --reporter $(REPORTER)13
7 unmodified lines
2122lib-cov:23 @jscoverage lib lib-cov2425docclean:26 rm -fr docs2719.PHONY: site test test-acceptance28.PHONY: docs docclean site test test-acceptance