needle.js 26 KB

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