Skip to content
Myr

response.js

This file

Path

lib/response.js

665 lines · 14.8 KiB · JavaScript

Last changed by

optimize res.format()TJ Holowaychukbefore adoption533b312

History of this file

Take it

12/*!3 * Express - response4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var fs = require('fs')13  , http = require('http')14  , path = require('path')15  , connect = require('connect')16  , utils = connect.utils17  , accept = require('./utils').accept18  , statusCodes = http.STATUS_CODES19  , send = connect.static.send20  , mime = require('mime')21  , basename = path.basename22  , join = path.join;2324/**25 * Response prototype.26 */2728var res = module.exports = {29  __proto__: http.ServerResponse.prototype30};3132/**33 * Set status `code`.34 *35 * @param {Number} code36 * @return {ServerResponse}37 * @api public38 */3940res.status = function(code){41  this.statusCode = code;42  return this;43};4445/**46 * Set Cache-Control to the given `type` and `options`.47 *48 * Options:49 *50 *  - `maxAge` in milliseconds51 *52 * @param {String} type53 * @param {Object} options54 * @return {ServerResponse}55 * @api public56 */5758res.cache = function(type, options){59  var val = type;60  options = options || {};61  if (options.maxAge) val += ', max-age=' + (options.maxAge / 1000); 62  return this.set('Cache-Control', val);63};6465/**66 * Send a response.67 *68 * Examples:69 *70 *     res.send(new Buffer('wahoo'));71 *     res.send({ some: 'json' });72 *     res.send('<p>some html</p>');73 *     res.send(404, 'Sorry, cant find that');74 *     res.send(404);75 *76 * @param {Mixed} body or status77 * @param {Mixed} body78 * @return {ServerResponse}79 * @api public80 */8182res.send = function(body){83  var req = this.req84    , head = 'HEAD' == req.method;8586  // allow status / body87  if (2 == arguments.length) {88    this.statusCode = body;89    body = arguments[1];90  }9192  switch (typeof body) {93    // response status94    case 'number':95      this.get('Content-Type') || this.contentType('.txt');96      this.statusCode = body;97      body = http.STATUS_CODES[body];98      break;99    // string defaulting to html100    case 'string':101      if (!this.get('Content-Type')) {102        this.charset = this.charset || 'utf-8';103        this.contentType('.html');104      }105      break;106    case 'boolean':107    case 'object':108      if (null == body) {109        body = '';110      } else if (Buffer.isBuffer(body)) {111        this.get('Content-Type') || this.contentType('.bin');112      } else {113        return this.json(body);114      }115      break;116  }117118  // populate Content-Length119  if (undefined !== body && !this.get('Content-Length')) {120    this.set('Content-Length', Buffer.isBuffer(body)121      ? body.length122      : Buffer.byteLength(body));123  }124125  // strip irrelevant headers126  if (204 == this.statusCode || 304 == this.statusCode) {127    this.removeHeader('Content-Type');128    this.removeHeader('Content-Length');129    body = '';130  }131132  // respond133  this.end(head ? null : body);134  return this;135};136137/**138 * Send JSON response.139 *140 * Examples:141 *142 *     res.json(null);143 *     res.json({ user: 'tj' });144 *     res.json(500, 'oh noes!');145 *     res.json(404, 'I dont have that');146 *147 * @param {Mixed} obj or status148 * @param {Mixed} obj149 * @return {ServerResponse}150 * @api public151 */152153res.json = function(obj){154  // allow status / body155  if (2 == arguments.length) {156    this.statusCode = obj;157    obj = arguments[1];158  }159160  var settings = this.app.settings161    , jsonp = settings['jsonp callback']162    , replacer = settings['json replacer']163    , spaces = settings['json spaces']164    , body = JSON.stringify(obj, replacer, spaces)165    , callback = this.req.query.callback;166167  this.charset = this.charset || 'utf-8';168  this.set('Content-Type', 'application/json');169170  if (callback && jsonp) {171    this.set('Content-Type', 'text/javascript');172    body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';173  }174175  return this.send(body);176};177178/**179 * Transfer the file at the given `path`.180 * 181 * Automatically sets the _Content-Type_ response header field.182 * The callback `fn(err)` is invoked when the transfer is complete183 * or when an error occurs. Be sure to check `res.sentHeader`184 * if you wish to attempt responding, as the header and some data185 * may have already been transferred.186 *187 * Options:188 *189 *   - `maxAge` defaulting to 0190 *   - `root`   root directory for relative filenames191 *192 * @param {String} path193 * @param {Object|Function} options or fn194 * @param {Function} fn195 * @api public196 */197198res.sendfile = function(path, options, fn){199  var self = this200    , req = self.req201    , next = this.req.next202    , options = options || {};203204  // support function as second arg205  if ('function' == typeof options) {206    fn = options;207    options = {};208  }209210  // callback211  options.callback = function(err){212    if (err) {213      // cast ENOENT214      if ('ENOENT' == err.code) err = 404;215216      // coerce numeric error to an Error217      // TODO: remove218      // TODO: remove docs for headerSent?219      if ('number' == typeof err) err = utils.error(err);220221      // ditch content-disposition to prevent funky responses222      if (!self.headerSent) self.removeHeader('Content-Disposition');223224      // woot! callback available225      if (fn) return fn(err);226227      // lost in limbo if there's no callback228      if (self.headerSent) return;229230      return req.next(err);231    }232233    fn && fn();234  };235236  // transfer237  options.path = encodeURIComponent(path);238  send(this.req, this, next, options);239};240241/**242 * Transfer the file at the given `path` as an attachment.243 *244 * Optionally providing an alternate attachment `filename`,245 * and optional callback `fn(err)`. The callback is invoked246 * when the data transfer is complete, or when an error has247 * ocurred. Be sure to check `res.headerSent` if you plan to respond.248 *249 * @param {String} path250 * @param {String|Function} filename or fn251 * @param {Function} fn252 * @api public253 */254255res.download = function(path, filename, fn){256  // support function as second arg257  if ('function' == typeof filename) {258    fn = filename;259    filename = null;260  }261262  return this.attachment(filename || path).sendfile(path, fn);263};264265/**266 * Set _Content-Type_ response header passed through `mime.lookup()`.267 *268 * Examples:269 *270 *     var filename = 'path/to/image.png';271 *     res.contentType(filename);272 *     // res.headers['Content-Type'] is now "image/png"273 *274 *     res.contentType('.html');275 *     res.contentType('html');276 *     res.contentType('json');277 *     res.contentType('png');278 *     res.type('png');279 *280 * @param {String} type281 * @return {ServerResponse} for chaining282 * @api public283 */284285res.contentType =286res.type = function(type){287  return this.set('Content-Type', mime.lookup(type));288};289290/**291 * Respond to the Acceptable formats using an `obj`292 * of mime-type callbacks.293 *294 * This method uses `req.accepted`, an array of295 * acceptable types ordered by their quality values.296 * When "Accept" is not present the _first_ callback297 * is invoked, otherwise the first match is used. When298 * no match is performed the server responds with299 * 406 "Not Acceptable".300 *301 * Content-Type is set for you, however if you choose302 * you may alter this within the callback using `res.type()`303 * or `res.set('Content-Type', ...)`.304 *305 *    res.format({306 *      'text/plain': function(){307 *        res.send('hey');308 *      },309 *    310 *      'text/html': function(){311 *        res.send('<p>hey</p>');312 *      },313 *    314 *      'appliation/json': function(){315 *        res.send({ message: 'hey' });316 *      }317 *    });318 *319 * In addition to canonicalized MIME types you may320 * also use extnames mapped to these types:321 *322 *    res.format({323 *      text: function(){324 *        res.send('hey');325 *      },326 *    327 *      html: function(){328 *        res.send('<p>hey</p>');329 *      },330 *    331 *      json: function(){332 *        res.send({ message: 'hey' });333 *      }334 *    });335 *336 * @param {Object} obj337 * @return {ServerResponse} for chaining338 * @api public339 */340341res.format = function(obj){342  var keys = Object.keys(obj)343    , types = []344    , req = this.req345    , next = req.next346    , accepted = req.accepted347    , acceptedlen = accepted.length348    , type349    , key;350351  // normalize extnames -> mime352  if (acceptedlen) {353    for (var i = 0; i < keys.length; ++i) {354      types.push(~keys[i].indexOf('/')355        ? keys[i]356        : mime.lookup(keys[i]));357    }358  }359360  // determine most acceptable format361  out:362  for (var i = 0; i < acceptedlen; ++i) {363    for (var j = 0, jlen = types.length; j < jlen; ++j) {364      if (accept(types[j].split('/'), accepted[i])) {365        key = keys[j];366        type = types[j];367        break out;368      }369    }370  }371372  // default to the first373  if (!acceptedlen) {374    key = keys[0];375    type = types[0];376  }377378  if (key) {379    this.set('Content-Type', type);380    obj[key](req, this, next);381  } else {382    var err = new Error('Not Acceptable');383    err.status = 406;384    err.types = types;385    next(err);386  }387388  return this;389};390391/**392 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.393 *394 * @param {String} filename395 * @return {ServerResponse}396 * @api public397 */398399res.attachment = function(filename){400  if (filename) this.type(filename);401  this.set('Content-Disposition', filename402    ? 'attachment; filename="' + basename(filename) + '"'403    : 'attachment');404  return this;405};406407/**408 * Set header `field` to `val`, or pass409 * an object of of header fields.410 *411 * Examples:412 *413 *    res.set('Accept', 'application/json');414 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });415 *416 * @param {String|Object} field417 * @param {String} val418 * @return {ServerResponse} for chaining419 * @api public420 */421422res.set = function(field, val){423  if (2 == arguments.length) {424    this.setHeader(field, val);425  } else {426    for (var key in field) {427      this.setHeader(key, field[key]);428    }429  }430  return this;431};432433/**434 * Get value for header `field`.435 *436 * @param {String} field437 * @return {String}438 * @api public439 */440441res.get = function(field){442  return this.getHeader(field);443};444445/**446 * Clear cookie `name`.447 *448 * @param {String} name449 * @param {Object} options450 * @param {ServerResponse} for chaining451 * @api public452 */453454res.clearCookie = function(name, options){455  var opts = { expires: new Date(1), path: '/' };456  return this.cookie(name, '', options457    ? utils.merge(opts, options)458    : opts);459};460461/**462 * Set a signed cookie with the given `name` and `val`.463 * See `res.cookie()` for details.464 *465 * @param {String} name466 * @param {String|Object} val467 * @param {Object} options468 * @api public469 */470471res.signedCookie = function(name, val, options){472  var secret = this.req.secret;473  if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');474  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);475  val = utils.sign(val, secret);476  return this.cookie(name, val, options);477};478479/**480 * Set cookie `name` to `val`, with the given `options`.481 *482 * Options:483 *484 *    - `maxAge`   max-age in milliseconds, converted to `expires`485 *    - `path`     defaults to "/"486 *487 * Examples:488 *489 *    // "Remember Me" for 15 minutes490 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });491 *492 *    // save as above493 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })494 *495 * @param {String} name496 * @param {String|Object} val497 * @param {Options} options498 * @api public499 */500501res.cookie = function(name, val, options){502  options = options || {};503  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);504  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);505  if (null == options.path) options.path = '/';506  var cookie = utils.serializeCookie(name, val, options);507  this.set('Set-Cookie', cookie);508  return this;509};510511/**512 * Redirect to the given `url` with optional response `status`513 * defaulting to 302.514 *515 * The given `url` can also be the name of a mapped url, for516 * example by default express supports "back" which redirects517 * to the _Referrer_ or _Referer_ headers or "/".518 *519 * Examples:520 *521 *    res.redirect('/foo/bar');522 *    res.redirect('http://example.com');523 *    res.redirect(301, 'http://example.com');524 *525 * Mounting:526 *527 *   When an application is mounted, and `res.redirect()`528 *   is given a path that does _not_ lead with "/". For 529 *   example suppose a "blog" app is mounted at "/blog",530 *   the following redirect would result in "/blog/login":531 *532 *      res.redirect('login');533 *534 *   While the leading slash would result in a redirect to "/login":535 *536 *      res.redirect('/login');537 *538 * @param {String} url539 * @param {Number} code540 * @api public541 */542543res.redirect = function(url){544  var app = this.app545    , req = this.req546    , head = 'HEAD' == req.method547    , status = 302548    , body;549550  // allow status / url551  if (2 == arguments.length) {552    status = url;553    url = arguments[1];554  }555556  // setup redirect map557  var map = { back: req.get('Referrer') || '/' };558559  // perform redirect560  url = map[url] || url;561562  // relative563  if (!~url.indexOf('://')) {564    var path = app.path();565566    // relative to path567    if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {568      url = req.path + '/' + url;569    // relative to mount-point570    } else if ('/' != url[0]) {571      url = path + '/' + url;572    }573574    // Absolute575    var host = req.get('Host');576    url = req.protocol + '://' + host + url;577  }578579  // Support text/{plain,html} by default580  this.format({581    'text/plain': function(){582      body = statusCodes[status] + '. Redirecting to ' + url;583    },584585    'text/html': function(){586      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';587    }588  })589590  // Respond591  this.statusCode = status;592  this.set('Location', url);593  this.end(head ? null : body);594};595596/**597 * Render `view` with the given `options` and optional callback `fn`.598 * When a callback function is given a response will _not_ be made599 * automatically, otherwise a response of _200_ and _text/html_ is given.600 *601 * Options:602 *  603 *  - `status`    Response status code (`res.statusCode`)604 *  - `charset`   Set the charset (`res.charset`)605 *606 * Reserved locals:607 *608 *  - `cache`     boolean hinting to the engine it should cache609 *  - `filename`  filename of the view being rendered610 *611 * @param  {String} view612 * @param  {Object|Function} options or callback function613 * @param  {Function} fn614 * @api public615 */616617res.render = function(view, options, fn){618  var self = this619    , options = options || {}620    , req = this.req621    , app = req.app;622623  // support callback function as second arg624  if ('function' == typeof options) {625    fn = options, options = {};626  }627628  function render() {629    // merge res.locals630    options.locals = self.locals;631632    // default callback to respond633    fn = fn || function(err, str){634      if (err) return req.next(err);635      self.send(str);636    };637638    // render639    app.render(view, options, fn);640  }641642  // invoke view callbacks643  var callbacks = app.viewCallbacks644    , pending = callbacks.length645    , len = pending646    , done;647648  if (len) {649    for (var i = 0; i < len; ++i) {650      callbacks[i](req, self, function(err){651        if (done) return;652653        if (err) {654          req.next(err);655          done = true;656          return;657        }658659        --pending || render();660      });661    }662  } else {663    render();664  }665};