request-stream.js
1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var http = require('http');
var Stream = require('stream');
var _ = require('underscore');
var defaults = {
host: 'localhost',
port: 8080,
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
function RequestStream(options) {
this._pending = {};
this.readable = true;
this.writeable = true;
this.options = _.defaults(options || {}, defaults);
}
RequestStream.prototype = new Stream();
RequestStream.prototype.constructor = RequestStream;
RequestStream.prototype.write = function write(packet, callback) {
var options = _.clone(this.options);
options.headers['Content-Length'] = packet.length;
var req = http.request(options, this._onResponse.bind(this, callback));
req.on('error', this._onError.bind(this, callback));
req.end(packet);
return true;
};
RequestStream.prototype._onError = function onError(callback, error) {
if (callback) {
callback(error);
}
};
RequestStream.prototype._onResponse = function onResponse(callback, response) {
var result = '';
response.on('data', function (data) { result += data; });
response.on('end', function () {
//console.log(result);
this.emit('data', result);
}.bind(this));
};
RequestStream.prototype.end = function end(string) {
if (string) {
this.write(string);
}
this.writable = false;
};
RequestStream.prototype.destroy = function destroy() {
this.writable = false;
this.emit('close');
};
RequestStream.prototype.destroySoon = function destroySoon() {
this.destroy();
};
module.exports = RequestStream;