Created
February 28, 2018 07:23
-
-
Save whiteinge/47cf6f0a1e8f4d8e58dfaac262bb927a to your computer and use it in GitHub Desktop.
Wrap Node's https.request() in an RxJS observable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var https = require('https'); | |
var Rx = require('rx'); | |
/** | |
Wrap Node's https.request() in an RxJS observable | |
**/ | |
function nodeRxXhr(options, postData) { | |
return Rx.Observable.create(function(obs) { | |
var req = https.request(options, function(res) { | |
res.setEncoding('utf8'); | |
var body = ''; | |
res.on('data', function(x) { body += x }); | |
res.on('end', function() { | |
obs.onNext({ | |
statusCode: res.statusCode, | |
httpVersion: res.httpVersion, | |
statusMessage: res.statusMessage, | |
headers: res.headers, | |
body: body, | |
}); | |
obs.onCompleted(); | |
}); | |
}); | |
req.on('error', function(err) { obs.onError(err) }); | |
if (postData != null) { req.write(postData); } | |
req.end(); | |
return function() { req.abort() }; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment