Connect

exports.hasBody()

Return true if the request has a body, otherwise return false.

Source

exports.hasBody = function(req) {
  var encoding = 'transfer-encoding' in req.headers;
  var length = 'content-length' in req.headers && req.headers['content-length'] !== '0';
  return encoding || length;
};

exports.mime()

Extract the mime type from the given request's
Content-Type header.

Source

exports.mime = function(req) {
  var str = req.headers['content-type'] || '';
  return str.split(';')[0];
};

exports.error()

Generate an Error from the given status code
and optional msg.

Source

exports.error = function(code, msg){
  var err = new Error(msg || http.STATUS_CODES[code]);
  err.status = code;
  return err;
};

exports.md5()

Return md5 hash of the given string and optional encoding,
defaulting to hex.

utils.md5('wahoo');
// => "e493298061761236c96b02ea6aa8a2ad"

Source

exports.md5 = function(str, encoding){
  return crypto
    .createHash('md5')
    .update(str, 'utf8')
    .digest(encoding || 'hex');
};

exports.merge()

Merge object b with object a.

var a = { foo: 'bar' }
  , b = { bar: 'baz' };

utils.merge(a, b);
// => { foo: 'bar', bar: 'baz' }

Source

exports.merge = function(a, b){
  if (a && b) {
    for (var key in b) {
      a[key] = b[key];
    }
  }
  return a;
};

exports.escape()

Escape the given string of html.

Source

exports.escape = function(html){
  return String(html)
    .replace(/&(?!\w+;)/g, '&')
    .replace(//g, '>')
    .replace(/"/g, '"');
};

exports.sign()

Sign the given val with secret.

Source

exports.sign = function(val, secret){
  console.warn('do not use utils.sign(), use https://github.com/visionmedia/node-cookie-signature')
  return val + '.' + crypto
    .createHmac('sha256', secret)
    .update(val)
    .digest('base64')
    .replace(/=+$/, '');
};

exports.unsign()

Unsign and decode the given val with secret,
returning false if the signature is invalid.

Source

exports.unsign = function(val, secret){
  console.warn('do not use utils.unsign(), use https://github.com/visionmedia/node-cookie-signature')
  var str = val.slice(0, val.lastIndexOf('.'));
  return exports.sign(str, secret) == val
    ? str
    : false;
};

exports.parseSignedCookies()

Parse signed cookies, returning an object
containing the decoded key/value pairs,
while removing the signed key from obj.

Source

exports.parseSignedCookies = function(obj, secret){
  var ret = {};
  Object.keys(obj).forEach(function(key){
    var val = obj[key];
    if (0 == val.indexOf('s:')) {
      val = signature.unsign(val.slice(2), secret);
      if (val) {
        ret[key] = val;
        delete obj[key];
      }
    }
  });
  return ret;
};

exports.parseSignedCookie()

Parse a signed cookie string, return the decoded value

Source

exports.parseSignedCookie = function(str, secret){
  return 0 == str.indexOf('s:')
    ? signature.unsign(str.slice(2), secret)
    : str;
};

exports.parseJSONCookies()

Parse JSON cookies.

Source

exports.parseJSONCookies = function(obj){
  Object.keys(obj).forEach(function(key){
    var val = obj[key];
    var res = exports.parseJSONCookie(val);
    if (res) obj[key] = res;
  });
  return obj;
};

exports.parseJSONCookie()

Parse JSON cookie string

Source

exports.parseJSONCookie = function(str) {
  if (0 == str.indexOf('j:')) {
    try {
      return JSON.parse(str.slice(2));
    } catch (err) {
      // no op
    }
  }
};

exports.pause

Pause data and end events on the given obj.
Middleware performing async tasks should utilize
this utility (or similar), to re-emit data once
the async operation has completed, otherwise these
events may be lost. Pause is only required for
node versions less than 10, and is replaced with
noop's otherwise.

 var pause = utils.pause(req);
 fs.readFile(path, function(){
    next();
    pause.resume();
 });

Source

exports.pause = exports.brokenPause
  ? require('pause')
  : function () {
    return {
      end: noop,
      resume: noop
    }
  }

exports.removeContentHeaders()

Strip Content-* headers from res.

Source

exports.removeContentHeaders = function(res){
  if (!res._headers) return;
  Object.keys(res._headers).forEach(function(field){
    if (0 == field.indexOf('content')) {
      res.removeHeader(field);
    }
  });
};

exports.conditionalGET()

Check if req is a conditional GET request.

Source

exports.conditionalGET = function(req) {
  return req.headers['if-modified-since']
    || req.headers['if-none-match'];
};

exports.unauthorized()

Respond with 401 "Unauthorized".

Source

exports.unauthorized = function(res, realm) {
  res.statusCode = 401;
  res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"');
  res.end('Unauthorized');
};

exports.notModified()

Respond with 304 "Not Modified".

Source

exports.notModified = function(res) {
  exports.removeContentHeaders(res);
  res.statusCode = 304;
  res.end();
};

exports.etag()

Return an ETag in the form of "<size>-<mtime>"
from the given stat.

Source

exports.etag = function(stat) {
  return '"' + stat.size + '-' + Number(stat.mtime) + '"';
};

exports.parseCacheControl()

Parse the given Cache-Control str.

Source

exports.parseCacheControl = function(str){
  var directives = str.split(',')
    , obj = {};

  for(var i = 0, len = directives.length; i < len; i++) {
    var parts = directives[i].split('=')
      , key = parts.shift().trim()
      , val = parseInt(parts.shift(), 10);

    obj[key] = isNaN(val) ? true : val;
  }

  return obj;
};

exports.parseUrl()

Parse the req url with memoization.

Source

exports.parseUrl = function(req){
  var parsed = req._parsedUrl;
  if (parsed && parsed.href == req.url) {
    return parsed;
  } else {
    parsed = parse(req.url);

    if (parsed.auth && !parsed.protocol && ~parsed.href.indexOf('//')) {
      // This parses pathnames, and a strange pathname like //r@e should work
      parsed = parse(req.url.replace(/@/g, '%40'));
    }

    return req._parsedUrl = parsed;
  }
};

exports.parseBytes

Parse byte size string.

Source

exports.parseBytes = require('bytes');

exports.normalizeSlashes()

Normalizes the path separator from system separator
to URL separator, aka /.

Source

exports.normalizeSlashes = function normalizeSlashes(path) {
  return path.split(sep).join('/');
};

function noop() {}