parse-headers.js 747 B

1234567891011121314151617181920212223242526272829303132
  1. var trim = function(string) {
  2. return string.replace(/^\s+|\s+$/g, '');
  3. }
  4. , isArray = function(arg) {
  5. return Object.prototype.toString.call(arg) === '[object Array]';
  6. }
  7. module.exports = function (headers) {
  8. if (!headers)
  9. return {}
  10. var result = {}
  11. var headersArr = trim(headers).split('\n')
  12. for (var i = 0; i < headersArr.length; i++) {
  13. var row = headersArr[i]
  14. var index = row.indexOf(':')
  15. , key = trim(row.slice(0, index)).toLowerCase()
  16. , value = trim(row.slice(index + 1))
  17. if (typeof(result[key]) === 'undefined') {
  18. result[key] = value
  19. } else if (isArray(result[key])) {
  20. result[key].push(value)
  21. } else {
  22. result[key] = [ result[key], value ]
  23. }
  24. }
  25. return result
  26. }