UNPKG

1.4 kBJavaScriptView Raw
1'use strict';
2
3var noop = require('./noop')
4 , xtend = require('xtend')
5 , getHeader = require('./get-header')
6 , HTTPParser = require('http-parser-js').HTTPParser;
7
8/**
9 * Since we want to support any HTTP methods (res.sendFile, res.json, etc.)
10 * we override the socket.write method. Doing so means we get a HTTP
11 * response string that needs to be parsed into an Object format so we
12 * can work with it. That's where this function comes in.
13 * @param {Buffer} httpContentBuffer
14 * @return {Object}
15 */
16module.exports = function getHttpResponseData (httpContentBuffer) {
17 var parser = new HTTPParser(HTTPParser.RESPONSE)
18 , httpData = {};
19
20 parser[HTTPParser.kOnMessageComplete] = noop;
21 parser[HTTPParser.kOnHeaders] = noop;
22
23 parser[HTTPParser.kOnHeadersComplete] = function (meta) {
24 httpData = xtend(httpData, meta);
25 };
26
27 parser[HTTPParser.kOnBody] = function (body, contentOffset, len) {
28 httpData = xtend(httpData, {
29 // The entire over the wire HTTP response
30 completeHttpBody: body.toString(),
31 // Just the "content" portion of the response
32 body: body.slice(contentOffset, contentOffset+len).toString()
33 });
34 };
35
36 parser.execute(httpContentBuffer);
37 parser.finish();
38 parser.close();
39
40 // Parsing is synchronous. The event handlers above will have fired by now
41 httpData.etag = getHeader(httpData.headers, 'etag');
42
43 return httpData;
44};