Permalink
Browse files

res.headers, seems to work in all the browsers

  • Loading branch information...
1 parent 105dcdb commit f51b5e4a4d6edf4c110e429e0bea8691334888de @substack committed Aug 20, 2011
Showing with 42 additions and 2 deletions.
  1. +0 −2 example/get/main.js
  2. +5 −0 example/streaming/main.js
  3. +37 −0 lib/response.js
View
@@ -3,8 +3,6 @@ var http = require('http');
http.get({ path : '/beep' }, function (res) {
var div = document.getElementById('result');
- div.innerHTML += JSON.stringify(res.headers) + '<br>';
-
res.on('data', function (buf) {
div.innerHTML += buf;
});
@@ -2,7 +2,12 @@ var http = require('http');
http.get({ path : '/doom' }, function (res) {
var div = document.getElementById('result');
+
+ for (var key in res.headers) {
+ div.innerHTML += key + ' => ' + res.getHeader(key) + '<br>';
+ }
div.innerHTML += res.statusCode + ': ';
+
if (!div.style) div.style = {};
div.style.color = 'rgb(80,80,80)';
View
@@ -11,10 +11,46 @@ var capable = {
status2 : true
};
+function parseHeaders (res) {
+ var lines = res.getAllResponseHeaders().split(/\r?\n/);
+ var headers = {};
+ for (var i = 0; i < lines.length; i++) {
+ var line = lines[i];
+ if (line === '') continue;
+
+ var m = line.match(/^([^:]+):\s*(.*)/);
+ if (m) {
+ var key = m[1].toLowerCase(), value = m[2];
+
+ if (headers[key] !== undefined) {
+ if ((Array.isArray && Array.isArray(headers[key]))
+ || headers[key] instanceof Array) {
+ headers[key].push(value);
+ }
+ else {
+ headers[key] = [ headers[key], value ];
+ }
+ }
+ else {
+ headers[key] = value;
+ }
+ }
+ else {
+ headers[line] = true;
+ }
+ }
+ return headers;
+}
+
+Response.prototype.getHeader = function (key) {
+ return this.headers[key.toLowerCase()];
+};
+
Response.prototype.handle = function (res) {
if (res.readyState === 2 && capable.status2) {
try {
this.statusCode = res.status;
+ this.headers = parseHeaders(res);
}
catch (err) {
capable.status2 = false;
@@ -28,6 +64,7 @@ Response.prototype.handle = function (res) {
try {
if (!this.statusCode) {
this.statusCode = res.status;
+ this.headers = parseHeaders(res);
this.emit('ready');
}
}

0 comments on commit f51b5e4

Please sign in to comment.