needle.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. //////////////////////////////////////////
  2. // Needle -- HTTP Client for Node.js
  3. // Written by Tomás Pollak <tomas@forkhq.com>
  4. // (c) 2012-2020 - Fork Ltd.
  5. // MIT Licensed
  6. //////////////////////////////////////////
  7. var fs = require('fs'),
  8. http = require('http'),
  9. https = require('https'),
  10. url = require('url'),
  11. stream = require('stream'),
  12. debug = require('debug')('needle'),
  13. stringify = require('./querystring').build,
  14. multipart = require('./multipart'),
  15. auth = require('./auth'),
  16. cookies = require('./cookies'),
  17. parsers = require('./parsers'),
  18. decoder = require('./decoder');
  19. //////////////////////////////////////////
  20. // variabilia
  21. var version = require('../package.json').version;
  22. var user_agent = 'Needle/' + version;
  23. user_agent += ' (Node.js ' + process.version + '; ' + process.platform + ' ' + process.arch + ')';
  24. var tls_options = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized secureProtocol checkServerIdentity family';
  25. // older versions of node (< 0.11.4) prevent the runtime from exiting
  26. // because of connections in keep-alive state. so if this is the case
  27. // we'll default new requests to set a Connection: close header.
  28. var close_by_default = !http.Agent || http.Agent.defaultMaxSockets != Infinity;
  29. // see if we have Object.assign. otherwise fall back to util._extend
  30. var extend = Object.assign ? Object.assign : require('util')._extend;
  31. // these are the status codes that Needle interprets as redirects.
  32. var redirect_codes = [301, 302, 303, 307, 308];
  33. //////////////////////////////////////////
  34. // decompressors for gzip/deflate/br bodies
  35. function bind_opts(fn, options) {
  36. return fn.bind(null, options);
  37. }
  38. var decompressors = {};
  39. try {
  40. var zlib = require('zlib');
  41. // Enable Z_SYNC_FLUSH to avoid Z_BUF_ERROR errors (Node PR #2595)
  42. var zlib_options = {
  43. flush: zlib.Z_SYNC_FLUSH,
  44. finishFlush: zlib.Z_SYNC_FLUSH
  45. };
  46. var br_options = {
  47. flush: zlib.BROTLI_OPERATION_FLUSH,
  48. finishFlush: zlib.BROTLI_OPERATION_FLUSH
  49. };
  50. decompressors['x-deflate'] = bind_opts(zlib.Inflate, zlib_options);
  51. decompressors['deflate'] = bind_opts(zlib.Inflate, zlib_options);
  52. decompressors['x-gzip'] = bind_opts(zlib.Gunzip, zlib_options);
  53. decompressors['gzip'] = bind_opts(zlib.Gunzip, zlib_options);
  54. if (typeof zlib.BrotliDecompress === 'function') {
  55. decompressors['br'] = bind_opts(zlib.BrotliDecompress, br_options);
  56. }
  57. } catch(e) { /* zlib not available */ }
  58. //////////////////////////////////////////
  59. // options and aliases
  60. var defaults = {
  61. // data
  62. boundary : '--------------------NODENEEDLEHTTPCLIENT',
  63. encoding : 'utf8',
  64. parse_response : 'all', // same as true. valid options: 'json', 'xml' or false/null
  65. proxy : null,
  66. // headers
  67. headers : {},
  68. accept : '*/*',
  69. user_agent : user_agent,
  70. // numbers
  71. open_timeout : 10000,
  72. response_timeout : 0,
  73. read_timeout : 0,
  74. follow_max : 0,
  75. stream_length : -1,
  76. // booleans
  77. compressed : false,
  78. decode_response : true,
  79. parse_cookies : true,
  80. follow_set_cookies : false,
  81. follow_set_referer : false,
  82. follow_keep_method : false,
  83. follow_if_same_host : false,
  84. follow_if_same_protocol : false,
  85. follow_if_same_location : false
  86. }
  87. var aliased = {
  88. options: {
  89. decode : 'decode_response',
  90. parse : 'parse_response',
  91. timeout : 'open_timeout',
  92. follow : 'follow_max'
  93. },
  94. inverted: {}
  95. }
  96. // only once, invert aliased keys so we can get passed options.
  97. Object.keys(aliased.options).map(function(k) {
  98. var value = aliased.options[k];
  99. aliased.inverted[value] = k;
  100. });
  101. //////////////////////////////////////////
  102. // helpers
  103. function keys_by_type(type) {
  104. return Object.keys(defaults).map(function(el) {
  105. if (defaults[el] !== null && defaults[el].constructor == type)
  106. return el;
  107. }).filter(function(el) { return el })
  108. }
  109. function parse_content_type(header) {
  110. if (!header || header === '') return {};
  111. var found, charset = 'utf8', arr = header.split(';');
  112. if (arr.length > 1 && (found = arr[1].match(/charset=(.+)/)))
  113. charset = found[1];
  114. return { type: arr[0], charset: charset };
  115. }
  116. function is_stream(obj) {
  117. return typeof obj.pipe === 'function';
  118. }
  119. function get_stream_length(stream, given_length, cb) {
  120. if (given_length > 0)
  121. return cb(given_length);
  122. if (stream.end !== void 0 && stream.end !== Infinity && stream.start !== void 0)
  123. return cb((stream.end + 1) - (stream.start || 0));
  124. fs.stat(stream.path, function(err, stat) {
  125. cb(stat ? stat.size - (stream.start || 0) : null);
  126. });
  127. }
  128. //////////////////////////////////////////
  129. // the main act
  130. function Needle(method, uri, data, options, callback) {
  131. // if (!(this instanceof Needle)) {
  132. // return new Needle(method, uri, data, options, callback);
  133. // }
  134. if (typeof uri !== 'string')
  135. throw new TypeError('URL must be a string, not ' + uri);
  136. this.method = method;
  137. this.uri = uri;
  138. this.data = data;
  139. if (typeof options == 'function') {
  140. this.callback = options;
  141. this.options = {};
  142. } else {
  143. this.callback = callback;
  144. this.options = options;
  145. }
  146. }
  147. Needle.prototype.setup = function(uri, options) {
  148. function get_option(key, fallback) {
  149. // if original is in options, return that value
  150. if (typeof options[key] != 'undefined') return options[key];
  151. // otherwise, return value from alias or fallback/undefined
  152. return typeof options[aliased.inverted[key]] != 'undefined'
  153. ? options[aliased.inverted[key]] : fallback;
  154. }
  155. function check_value(expected, key) {
  156. var value = get_option(key),
  157. type = typeof value;
  158. if (type != 'undefined' && type != expected)
  159. throw new TypeError(type + ' received for ' + key + ', but expected a ' + expected);
  160. return (type == expected) ? value : defaults[key];
  161. }
  162. //////////////////////////////////////////////////
  163. // the basics
  164. var config = {
  165. http_opts : {
  166. localAddress: get_option('localAddress', undefined)
  167. }, // passed later to http.request() directly
  168. headers : {},
  169. output : options.output,
  170. proxy : get_option('proxy', defaults.proxy),
  171. parser : get_option('parse_response', defaults.parse_response),
  172. encoding : options.encoding || (options.multipart ? 'binary' : defaults.encoding)
  173. }
  174. keys_by_type(Boolean).forEach(function(key) {
  175. config[key] = check_value('boolean', key);
  176. })
  177. keys_by_type(Number).forEach(function(key) {
  178. config[key] = check_value('number', key);
  179. })
  180. // populate http_opts with given TLS options
  181. tls_options.split(' ').forEach(function(key) {
  182. if (typeof options[key] != 'undefined') {
  183. config.http_opts[key] = options[key];
  184. if (typeof options.agent == 'undefined')
  185. config.http_opts.agent = false; // otherwise tls options are skipped
  186. }
  187. });
  188. //////////////////////////////////////////////////
  189. // headers, cookies
  190. for (var key in defaults.headers)
  191. config.headers[key] = defaults.headers[key];
  192. config.headers['accept'] = options.accept || defaults.accept;
  193. config.headers['user-agent'] = options.user_agent || defaults.user_agent;
  194. if (options.content_type)
  195. config.headers['content-type'] = options.content_type;
  196. // set connection header if opts.connection was passed, or if node < 0.11.4 (close)
  197. if (options.connection || close_by_default)
  198. config.headers['connection'] = options.connection || 'close';
  199. if ((options.compressed || defaults.compressed) && typeof zlib != 'undefined')
  200. config.headers['accept-encoding'] = decompressors['br'] ? 'gzip, deflate, br' : 'gzip, deflate';
  201. if (options.cookies)
  202. config.headers['cookie'] = cookies.write(options.cookies);
  203. //////////////////////////////////////////////////
  204. // basic/digest auth
  205. if (uri.match(/[^\/]@/)) { // url contains user:pass@host, so parse it.
  206. var parts = (url.parse(uri).auth || '').split(':');
  207. options.username = parts[0];
  208. options.password = parts[1];
  209. }
  210. if (options.username) {
  211. if (options.auth && (options.auth == 'auto' || options.auth == 'digest')) {
  212. config.credentials = [options.username, options.password];
  213. } else {
  214. config.headers['authorization'] = auth.basic(options.username, options.password);
  215. }
  216. }
  217. // if proxy is present, set auth header from either url or proxy_user option.
  218. if (config.proxy) {
  219. if (config.proxy.indexOf('http') === -1)
  220. config.proxy = 'http://' + config.proxy;
  221. if (config.proxy.indexOf('@') !== -1) {
  222. var proxy = (url.parse(config.proxy).auth || '').split(':');
  223. options.proxy_user = proxy[0];
  224. options.proxy_pass = proxy[1];
  225. }
  226. if (options.proxy_user)
  227. config.headers['proxy-authorization'] = auth.basic(options.proxy_user, options.proxy_pass);
  228. }
  229. // now that all our headers are set, overwrite them if instructed.
  230. for (var h in options.headers)
  231. config.headers[h.toLowerCase()] = options.headers[h];
  232. config.uri_modifier = get_option('uri_modifier', null);
  233. return config;
  234. }
  235. Needle.prototype.start = function() {
  236. var out = new stream.PassThrough({ objectMode: false }),
  237. uri = this.uri,
  238. data = this.data,
  239. method = this.method,
  240. callback = (typeof this.options == 'function') ? this.options : this.callback,
  241. options = this.options || {};
  242. // if no 'http' is found on URL, prepend it.
  243. if (uri.indexOf('http') === -1)
  244. uri = uri.replace(/^(\/\/)?/, 'http://');
  245. var self = this, body, waiting = false, config = this.setup(uri, options);
  246. // unless options.json was set to false, assume boss also wants JSON if content-type matches.
  247. var json = options.json || (options.json !== false && config.headers['content-type'] == 'application/json');
  248. if (data) {
  249. if (options.multipart) { // boss says we do multipart. so we do it.
  250. var boundary = options.boundary || defaults.boundary;
  251. waiting = true;
  252. multipart.build(data, boundary, function(err, parts) {
  253. if (err) throw(err);
  254. config.headers['content-type'] = 'multipart/form-data; boundary=' + boundary;
  255. next(parts);
  256. });
  257. } else if (is_stream(data)) {
  258. if (method.toUpperCase() == 'GET')
  259. throw new Error('Refusing to pipe() a stream via GET. Did you mean .post?');
  260. if (config.stream_length > 0 || (config.stream_length === 0 && data.path)) {
  261. // ok, let's get the stream's length and set it as the content-length header.
  262. // this prevents some servers from cutting us off before all the data is sent.
  263. waiting = true;
  264. get_stream_length(data, config.stream_length, function(length) {
  265. data.length = length;
  266. next(data);
  267. })
  268. } else {
  269. // if the boss doesn't want us to get the stream's length, or if it doesn't
  270. // have a file descriptor for that purpose, then just head on.
  271. body = data;
  272. }
  273. } else if (Buffer.isBuffer(data)) {
  274. body = data; // use the raw buffer as request body.
  275. } else if (method.toUpperCase() == 'GET' && !json) {
  276. // append the data to the URI as a querystring.
  277. uri = uri.replace(/\?.*|$/, '?' + stringify(data));
  278. } else { // string or object data, no multipart.
  279. // if string, leave it as it is, otherwise, stringify.
  280. body = (typeof(data) === 'string') ? data
  281. : json ? JSON.stringify(data) : stringify(data);
  282. // ensure we have a buffer so bytecount is correct.
  283. body = Buffer.from(body, config.encoding);
  284. }
  285. }
  286. function next(body) {
  287. if (body) {
  288. if (body.length) config.headers['content-length'] = body.length;
  289. // if no content-type was passed, determine if json or not.
  290. if (!config.headers['content-type']) {
  291. config.headers['content-type'] = json
  292. ? 'application/json; charset=utf-8'
  293. : 'application/x-www-form-urlencoded'; // no charset says W3 spec.
  294. }
  295. }
  296. // unless a specific accept header was set, assume json: true wants JSON back.
  297. if (options.json && (!options.accept && !(options.headers || {}).accept))
  298. config.headers['accept'] = 'application/json';
  299. self.send_request(1, method, uri, config, body, out, callback);
  300. }
  301. if (!waiting) next(body);
  302. return out;
  303. }
  304. Needle.prototype.get_request_opts = function(method, uri, config) {
  305. var opts = config.http_opts,
  306. proxy = config.proxy,
  307. remote = proxy ? url.parse(proxy) : url.parse(uri);
  308. opts.protocol = remote.protocol;
  309. opts.host = remote.hostname;
  310. opts.port = remote.port || (remote.protocol == 'https:' ? 443 : 80);
  311. opts.path = proxy ? uri : remote.pathname + (remote.search || '');
  312. opts.method = method;
  313. opts.headers = config.headers;
  314. if (!opts.headers['host']) {
  315. // if using proxy, make sure the host header shows the final destination
  316. var target = proxy ? url.parse(uri) : remote;
  317. opts.headers['host'] = target.hostname;
  318. // and if a non standard port was passed, append it to the port header
  319. if (target.port && [80, 443].indexOf(target.port) === -1) {
  320. opts.headers['host'] += ':' + target.port;
  321. }
  322. }
  323. return opts;
  324. }
  325. Needle.prototype.should_follow = function(location, config, original) {
  326. if (!location) return false;
  327. // returns true if location contains matching property (host or protocol)
  328. function matches(property) {
  329. var property = original[property];
  330. return location.indexOf(property) !== -1;
  331. }
  332. // first, check whether the requested location is actually different from the original
  333. if (!config.follow_if_same_location && location === original)
  334. return false;
  335. if (config.follow_if_same_host && !matches('host'))
  336. return false; // host does not match, so not following
  337. if (config.follow_if_same_protocol && !matches('protocol'))
  338. return false; // procotol does not match, so not following
  339. return true;
  340. }
  341. Needle.prototype.send_request = function(count, method, uri, config, post_data, out, callback) {
  342. if (typeof config.uri_modifier === 'function') {
  343. var modified_uri = config.uri_modifier(uri);
  344. debug('Modifying request URI', uri + ' => ' + modified_uri);
  345. uri = modified_uri;
  346. }
  347. var timer,
  348. returned = 0,
  349. self = this,
  350. request_opts = this.get_request_opts(method, uri, config),
  351. protocol = request_opts.protocol == 'https:' ? https : http;
  352. function done(err, resp) {
  353. if (returned++ > 0)
  354. return debug('Already finished, stopping here.');
  355. if (timer) clearTimeout(timer);
  356. request.removeListener('error', had_error);
  357. if (callback)
  358. return callback(err, resp, resp ? resp.body : undefined);
  359. // NOTE: this event used to be called 'end', but the behaviour was confusing
  360. // when errors ocurred, because the stream would still emit an 'end' event.
  361. out.emit('done', err);
  362. }
  363. function had_error(err) {
  364. debug('Request error', err);
  365. out.emit('err', err);
  366. done(err || new Error('Unknown error when making request.'));
  367. }
  368. function set_timeout(type, milisecs) {
  369. if (timer) clearTimeout(timer);
  370. if (milisecs <= 0) return;
  371. timer = setTimeout(function() {
  372. out.emit('timeout', type);
  373. request.abort();
  374. // also invoke done() to terminate job on read_timeout
  375. if (type == 'read') done(new Error(type + ' timeout'));
  376. }, milisecs);
  377. }
  378. // handle errors on the underlying socket, that may be closed while writing
  379. // for an example case, see test/long_string_spec.js. we make sure this
  380. // scenario ocurred by verifying the socket's writable & destroyed states.
  381. function on_socket_end() {
  382. if (returned && !this.writable && this.destroyed === false) {
  383. this.destroy();
  384. had_error(new Error('Remote end closed socket abruptly.'))
  385. }
  386. }
  387. debug('Making request #' + count, request_opts);
  388. var request = protocol.request(request_opts, function(resp) {
  389. var headers = resp.headers;
  390. debug('Got response', resp.statusCode, headers);
  391. out.emit('response', resp);
  392. set_timeout('read', config.read_timeout);
  393. // if we got cookies, parse them unless we were instructed not to. make sure to include any
  394. // cookies that might have been set on previous redirects.
  395. if (config.parse_cookies && (headers['set-cookie'] || config.previous_resp_cookies)) {
  396. resp.cookies = extend(config.previous_resp_cookies || {}, cookies.read(headers['set-cookie']));
  397. debug('Got cookies', resp.cookies);
  398. }
  399. // if redirect code is found, determine if we should follow it according to the given options.
  400. if (redirect_codes.indexOf(resp.statusCode) !== -1 && self.should_follow(headers.location, config, uri)) {
  401. // clear timer before following redirects to prevent unexpected setTimeout consequence
  402. clearTimeout(timer);
  403. if (count <= config.follow_max) {
  404. out.emit('redirect', headers.location);
  405. // unless 'follow_keep_method' is true, rewrite the request to GET before continuing.
  406. if (!config.follow_keep_method) {
  407. method = 'GET';
  408. post_data = null;
  409. delete config.headers['content-length']; // in case the original was a multipart POST request.
  410. }
  411. // if follow_set_cookies is true, insert cookies in the next request's headers.
  412. // we set both the original request cookies plus any response cookies we might have received.
  413. if (config.follow_set_cookies) {
  414. var request_cookies = cookies.read(config.headers['cookie']);
  415. config.previous_resp_cookies = resp.cookies;
  416. if (Object.keys(request_cookies).length || Object.keys(resp.cookies || {}).length) {
  417. config.headers['cookie'] = cookies.write(extend(request_cookies, resp.cookies));
  418. }
  419. } else if (config.headers['cookie']) {
  420. debug('Clearing original request cookie', config.headers['cookie']);
  421. delete config.headers['cookie'];
  422. }
  423. if (config.follow_set_referer)
  424. config.headers['referer'] = encodeURI(uri); // the original, not the destination URL.
  425. config.headers['host'] = null; // clear previous Host header to avoid conflicts.
  426. debug('Redirecting to ' + url.resolve(uri, headers.location));
  427. return self.send_request(++count, method, url.resolve(uri, headers.location), config, post_data, out, callback);
  428. } else if (config.follow_max > 0) {
  429. return done(new Error('Max redirects reached. Possible loop in: ' + headers.location));
  430. }
  431. }
  432. // if auth is requested and credentials were not passed, resend request, provided we have user/pass.
  433. if (resp.statusCode == 401 && headers['www-authenticate'] && config.credentials) {
  434. if (!config.headers['authorization']) { // only if authentication hasn't been sent
  435. var auth_header = auth.header(headers['www-authenticate'], config.credentials, request_opts);
  436. if (auth_header) {
  437. config.headers['authorization'] = auth_header;
  438. return self.send_request(count, method, uri, config, post_data, out, callback);
  439. }
  440. }
  441. }
  442. // ok, so we got a valid (non-redirect & authorized) response. let's notify the stream guys.
  443. out.emit('header', resp.statusCode, headers);
  444. out.emit('headers', headers);
  445. var pipeline = [],
  446. mime = parse_content_type(headers['content-type']),
  447. text_response = mime.type && mime.type.indexOf('text/') != -1;
  448. // To start, if our body is compressed and we're able to inflate it, do it.
  449. if (headers['content-encoding'] && decompressors[headers['content-encoding']]) {
  450. var decompressor = decompressors[headers['content-encoding']]();
  451. // make sure we catch errors triggered by the decompressor.
  452. decompressor.on('error', had_error);
  453. pipeline.push(decompressor);
  454. }
  455. // If parse is enabled and we have a parser for it, then go for it.
  456. if (config.parser && parsers[mime.type]) {
  457. // If a specific parser was requested, make sure we don't parse other types.
  458. var parser_name = config.parser.toString().toLowerCase();
  459. if (['xml', 'json'].indexOf(parser_name) == -1 || parsers[mime.type].name == parser_name) {
  460. // OK, so either we're parsing all content types or the one requested matches.
  461. out.parser = parsers[mime.type].name;
  462. pipeline.push(parsers[mime.type].fn());
  463. // Set objectMode on out stream to improve performance.
  464. out._writableState.objectMode = true;
  465. out._readableState.objectMode = true;
  466. }
  467. // If we're not parsing, and unless decoding was disabled, we'll try
  468. // decoding non UTF-8 bodies to UTF-8, using the iconv-lite library.
  469. } else if (text_response && config.decode_response
  470. && mime.charset) {
  471. pipeline.push(decoder(mime.charset));
  472. }
  473. // And `out` is the stream we finally push the decoded/parsed output to.
  474. pipeline.push(out);
  475. // Now, release the kraken!
  476. var tmp = resp;
  477. while (pipeline.length) {
  478. tmp = tmp.pipe(pipeline.shift());
  479. }
  480. // If the user has requested and output file, pipe the output stream to it.
  481. // In stream mode, we will still get the response stream to play with.
  482. if (config.output && resp.statusCode == 200) {
  483. // for some reason, simply piping resp to the writable stream doesn't
  484. // work all the time (stream gets cut in the middle with no warning).
  485. // so we'll manually need to do the readable/write(chunk) trick.
  486. var file = fs.createWriteStream(config.output);
  487. file.on('error', had_error);
  488. out.on('end', function() {
  489. if (file.writable) file.end();
  490. });
  491. file.on('close', function() {
  492. delete out.file;
  493. })
  494. out.on('readable', function() {
  495. var chunk;
  496. while ((chunk = this.read()) !== null) {
  497. if (file.writable) file.write(chunk);
  498. // if callback was requested, also push it to resp.body
  499. if (resp.body) resp.body.push(chunk);
  500. }
  501. })
  502. out.file = file;
  503. }
  504. // Only aggregate the full body if a callback was requested.
  505. if (callback) {
  506. resp.raw = [];
  507. resp.body = [];
  508. resp.bytes = 0;
  509. // Gather and count the amount of (raw) bytes using a PassThrough stream.
  510. var clean_pipe = new stream.PassThrough();
  511. resp.pipe(clean_pipe);
  512. clean_pipe.on('readable', function() {
  513. var chunk;
  514. while ((chunk = this.read()) != null) {
  515. resp.bytes += chunk.length;
  516. resp.raw.push(chunk);
  517. }
  518. })
  519. // Listen on the 'readable' event to aggregate the chunks, but only if
  520. // file output wasn't requested. Otherwise we'd have two stream readers.
  521. if (!config.output || resp.statusCode != 200) {
  522. out.on('readable', function() {
  523. var chunk;
  524. while ((chunk = this.read()) !== null) {
  525. // We're either pushing buffers or objects, never strings.
  526. if (typeof chunk == 'string') chunk = Buffer.from(chunk);
  527. // Push all chunks to resp.body. We'll bind them in resp.end().
  528. resp.body.push(chunk);
  529. }
  530. })
  531. }
  532. }
  533. // And set the .body property once all data is in.
  534. out.on('end', function() {
  535. if (resp.body) { // callback mode
  536. // we want to be able to access to the raw data later, so keep a reference.
  537. resp.raw = Buffer.concat(resp.raw);
  538. // if parse was successful, we should have an array with one object
  539. if (resp.body[0] !== undefined && !Buffer.isBuffer(resp.body[0])) {
  540. // that's our body right there.
  541. resp.body = resp.body[0];
  542. // set the parser property on our response. we may want to check.
  543. if (out.parser) resp.parser = out.parser;
  544. } else { // we got one or several buffers. string or binary.
  545. resp.body = Buffer.concat(resp.body);
  546. // if we're here and parsed is true, it means we tried to but it didn't work.
  547. // so given that we got a text response, let's stringify it.
  548. if (text_response || out.parser) {
  549. resp.body = resp.body.toString();
  550. }
  551. }
  552. }
  553. // if an output file is being written to, make sure the callback
  554. // is triggered after all data has been written to it.
  555. if (out.file) {
  556. out.file.on('close', function() {
  557. done(null, resp, resp.body);
  558. })
  559. } else { // elvis has left the building.
  560. done(null, resp, resp.body);
  561. }
  562. });
  563. }); // end request call
  564. // unless open_timeout was disabled, set a timeout to abort the request.
  565. set_timeout('open', config.open_timeout);
  566. // handle errors on the request object. things might get bumpy.
  567. request.on('error', had_error);
  568. // make sure timer is cleared if request is aborted (issue #257)
  569. request.once('abort', function() {
  570. if (timer) clearTimeout(timer);
  571. })
  572. // handle socket 'end' event to ensure we don't get delayed EPIPE errors.
  573. request.once('socket', function(socket) {
  574. if (socket.connecting) {
  575. socket.once('connect', function() {
  576. set_timeout('response', config.response_timeout);
  577. })
  578. } else {
  579. set_timeout('response', config.response_timeout);
  580. }
  581. // console.log(socket);
  582. if (!socket.on_socket_end) {
  583. socket.on_socket_end = on_socket_end;
  584. socket.once('end', function() { process.nextTick(on_socket_end.bind(socket)) });
  585. }
  586. })
  587. if (post_data) {
  588. if (is_stream(post_data)) {
  589. post_data.pipe(request);
  590. } else {
  591. request.write(post_data, config.encoding);
  592. request.end();
  593. }
  594. } else {
  595. request.end();
  596. }
  597. out.request = request;
  598. return out;
  599. }
  600. //////////////////////////////////////////
  601. // exports
  602. if (typeof Promise !== 'undefined') {
  603. module.exports = function() {
  604. var verb, args = [].slice.call(arguments);
  605. if (args[0].match(/\.|\//)) // first argument looks like a URL
  606. verb = (args.length > 2) ? 'post' : 'get';
  607. else
  608. verb = args.shift();
  609. if (verb.match(/get|head/) && args.length == 2)
  610. args.splice(1, 0, null); // assume no data if head/get with two args (url, options)
  611. return new Promise(function(resolve, reject) {
  612. module.exports.request(verb, args[0], args[1], args[2], function(err, resp) {
  613. return err ? reject(err) : resolve(resp);
  614. });
  615. })
  616. }
  617. }
  618. module.exports.version = version;
  619. module.exports.defaults = function(obj) {
  620. for (var key in obj) {
  621. var target_key = aliased.options[key] || key;
  622. if (defaults.hasOwnProperty(target_key) && typeof obj[key] != 'undefined') {
  623. if (target_key != 'parse_response' && target_key != 'proxy') {
  624. // ensure type matches the original, except for proxy/parse_response that can be null/bool or string
  625. var valid_type = defaults[target_key].constructor.name;
  626. if (obj[key].constructor.name != valid_type)
  627. throw new TypeError('Invalid type for ' + key + ', should be ' + valid_type);
  628. }
  629. defaults[target_key] = obj[key];
  630. } else {
  631. throw new Error('Invalid property for defaults:' + target_key);
  632. }
  633. }
  634. return defaults;
  635. }
  636. 'head get'.split(' ').forEach(function(method) {
  637. module.exports[method] = function(uri, options, callback) {
  638. return new Needle(method, uri, null, options, callback).start();
  639. }
  640. })
  641. 'post put patch delete'.split(' ').forEach(function(method) {
  642. module.exports[method] = function(uri, data, options, callback) {
  643. return new Needle(method, uri, data, options, callback).start();
  644. }
  645. })
  646. module.exports.request = function(method, uri, data, opts, callback) {
  647. return new Needle(method, uri, data, opts, callback).start();
  648. };