Skip to content

Instantly share code, notes, and snippets.

@whiteinge
Created February 28, 2018 07:23
Show Gist options
  • Save whiteinge/47cf6f0a1e8f4d8e58dfaac262bb927a to your computer and use it in GitHub Desktop.
Save whiteinge/47cf6f0a1e8f4d8e58dfaac262bb927a to your computer and use it in GitHub Desktop.
Wrap Node's https.request() in an RxJS observable
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