needle.js 28 KB

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