• Home
Name Date Size #Lines LOC

..--

node_modules/get-stream/12-May-2024-325249

index.jsD12-May-20248.8 KiB365284

licenseD12-May-20241.1 KiB2217

package.jsonD12-May-20242.3 KiB111110

readme.mdD12-May-20249.2 KiB336205

readme.md

1<h1 align="center">
2	<br>
3	<img width="360" src="https://rawgit.com/sindresorhus/got/master/media/logo.svg" alt="got">
4	<br>
5	<br>
6	<br>
7</h1>
8
9> Simplified HTTP requests
10
11[![Build Status](https://travis-ci.org/sindresorhus/got.svg?branch=master)](https://travis-ci.org/sindresorhus/got) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/got/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/got?branch=master) [![Downloads](https://img.shields.io/npm/dm/got.svg)](https://npmjs.com/got)
12
13A nicer interface to the built-in [`http`](http://nodejs.org/api/http.html) module.
14
15It supports following redirects, promises, streams, retries, automagically handling gzip/deflate and some convenience options.
16
17Created because [`request`](https://github.com/request/request) is bloated *(several megabytes!)*.
18
19
20## Install
21
22**WARNING: Node.js 4 or higher is required for got@6 and above.** For older Node.js versions use [got@5](https://github.com/sindresorhus/got/tree/v5.x).
23
24```
25$ npm install --save got
26```
27
28
29## Usage
30
31```js
32const fs = require('fs');
33const got = require('got');
34
35got('todomvc.com')
36	.then(response => {
37		console.log(response.body);
38		//=> '<!doctype html> ...'
39	})
40	.catch(error => {
41		console.log(error.response.body);
42		//=> 'Internal server error ...'
43	});
44
45// Streams
46got.stream('todomvc.com').pipe(fs.createWriteStream('index.html'));
47
48// For POST, PUT and PATCH methods got.stream returns a WritableStream
49fs.createReadStream('index.html').pipe(got.stream.post('todomvc.com'));
50```
51
52
53### API
54
55It's a `GET` request by default, but can be changed in `options`.
56
57#### got(url, [options])
58
59Returns a Promise for a `response` object with a `body` property, a `url` property with the request URL or the final URL after redirects, and a `requestUrl` property with the original request URL.
60
61##### url
62
63Type: `string`, `object`
64
65The URL to request or a [`http.request` options](https://nodejs.org/api/http.html#http_http_request_options_callback) object.
66
67Properties from `options` will override properties in the parsed `url`.
68
69##### options
70
71Type: `object`
72
73Any of the [`http.request`](http://nodejs.org/api/http.html#http_http_request_options_callback) options.
74
75###### body
76
77Type: `string`, `buffer`, `readableStream`, `object`
78
79*This is mutually exclusive with stream mode.*
80
81Body that will be sent with a `POST` request.
82
83If present in `options` and `options.method` is not set, `options.method` will be set to `POST`.
84
85If `content-length` or `transfer-encoding` is not set in `options.headers` and `body` is a string or buffer, `content-length` will be set to the body length.
86
87If `body` is a plain object, it will be stringified with [`querystring.stringify`](https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) and sent as `application/x-www-form-urlencoded`.
88
89###### encoding
90
91Type: `string`, `null`<br>
92Default: `'utf8'`
93
94Encoding to be used on `setEncoding` of the response data. If `null`, the body is returned as a Buffer.
95
96###### json
97
98Type: `boolean`<br>
99Default: `false`
100
101*This is mutually exclusive with stream mode.*
102
103Parse response body with `JSON.parse` and set `accept` header to `application/json`.
104
105###### query
106
107Type: `string`, `object`<br>
108
109Query string object that will be added to the request URL. This will override the query string in `url`.
110
111###### timeout
112
113Type: `number`, `object`
114
115Milliseconds to wait for a server to send response headers before aborting request with `ETIMEDOUT` error.
116
117Option accepts `object` with separate `connect` and `socket` fields for connection and socket inactivity timeouts.
118
119###### retries
120
121Type: `number`, `function`<br>
122Default: `5`
123
124Number of request retries when network errors happens. Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 0).
125
126Option accepts `function` with `retry` and `error` arguments. Function must return delay in milliseconds (`0` return value cancels retry).
127
128**Note:** if `retries` is `number`, `ENOTFOUND` and `ENETUNREACH` error will not be retried (see full list in [`is-retry-allowed`](https://github.com/floatdrop/is-retry-allowed/blob/master/index.js#L12) module).
129
130###### followRedirect
131
132Type: `boolean`<br>
133Default: `true`
134
135Defines if redirect responses should be followed automatically.
136
137
138#### Streams
139
140#### got.stream(url, [options])
141
142`stream` method will return Duplex stream with additional events:
143
144##### .on('request', request)
145
146`request` event to get the request object of the request.
147
148**Tip**: You can use `request` event to abort request:
149
150```js
151got.stream('github.com')
152	.on('request', req => setTimeout(() => req.abort(), 50));
153```
154
155##### .on('response', response)
156
157`response` event to get the response object of the final request.
158
159##### .on('redirect', response, nextOptions)
160
161`redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location.
162
163##### .on('error', error, body, response)
164
165`error` event emitted in case of protocol error (like `ENOTFOUND` etc.) or status error (4xx or 5xx). The second argument is the body of the server response in case of status error. The third argument is response object.
166
167#### got.get(url, [options])
168#### got.post(url, [options])
169#### got.put(url, [options])
170#### got.patch(url, [options])
171#### got.head(url, [options])
172#### got.delete(url, [options])
173
174Sets `options.method` to the method name and makes a request.
175
176
177## Errors
178
179Each error contains (if available) `statusCode`, `statusMessage`, `host`, `hostname`, `method` and `path` properties to make debugging easier.
180
181In Promise mode, the `response` is attached to the error.
182
183#### got.RequestError
184
185When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`.
186
187#### got.ReadError
188
189When reading from response stream fails.
190
191#### got.ParseError
192
193When `json` option is enabled and `JSON.parse` fails.
194
195#### got.HTTPError
196
197When server response code is not 2xx. Contains `statusCode` and `statusMessage`.
198
199#### got.MaxRedirectsError
200
201When server redirects you more than 10 times.
202
203
204## Proxies
205
206You can use the [`tunnel`](https://github.com/koichik/node-tunnel) module with the `agent` option to work with proxies:
207
208```js
209const got = require('got');
210const tunnel = require('tunnel');
211
212got('todomvc.com', {
213	agent: tunnel.httpOverHttp({
214		proxy: {
215			host: 'localhost'
216		}
217	})
218});
219```
220
221
222## Cookies
223
224You can use the [`cookie`](https://github.com/jshttp/cookie) module to include cookies in a request:
225
226```js
227const got = require('got');
228const cookie = require('cookie');
229
230got('google.com', {
231	headers: {
232		cookie: cookie.serialize('foo', 'bar')
233	}
234});
235```
236
237
238## Form data
239
240You can use the [`form-data`](https://github.com/form-data/form-data) module to create POST request with form data:
241
242```js
243const fs = require('fs');
244const got = require('got');
245const FormData = require('form-data');
246const form = new FormData();
247
248form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
249
250got.post('google.com', {
251	body: form
252});
253```
254
255
256## OAuth
257
258You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) module to create a signed OAuth request:
259
260```js
261const got = require('got');
262const crypto  = require('crypto');
263const OAuth = require('oauth-1.0a');
264
265const oauth = OAuth({
266	consumer: {
267		key: process.env.CONSUMER_KEY,
268		secret: process.env.CONSUMER_SECRET
269	},
270	signature_method: 'HMAC-SHA1',
271	hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
272});
273
274const token = {
275	key: process.env.ACCESS_TOKEN,
276	secret: process.env.ACCESS_TOKEN_SECRET
277};
278
279const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
280
281got(url, {
282	headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)),
283	json: true
284});
285```
286
287
288## Unix Domain Sockets
289
290Requests can also be sent via [unix domain sockets](http://serverfault.com/questions/124517/whats-the-difference-between-unix-socket-and-tcp-ip-socket). Use the following URL scheme: `PROTOCOL://unix:SOCKET:PATH`.
291
292- `PROTOCOL` - `http` or `https` *(optional)*
293- `SOCKET` - absolute path to a unix domain socket, e.g. `/var/run/docker.sock`
294- `PATH` - request path, e.g. `/v2/keys`
295
296```js
297got('http://unix:/var/run/docker.sock:/containers/json');
298
299// or without protocol (http by default)
300got('unix:/var/run/docker.sock:/containers/json');
301```
302
303
304## Tip
305
306It's a good idea to set the `'user-agent'` header so the provider can more easily see how their resource is used. By default, it's the URL to this repo.
307
308```js
309const got = require('got');
310const pkg = require('./package.json');
311
312got('todomvc.com', {
313	headers: {
314		'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)`
315	}
316});
317```
318
319
320## Related
321
322- [gh-got](https://github.com/sindresorhus/gh-got) - Convenience wrapper for interacting with the GitHub API
323- [travis-got](https://github.com/samverschueren/travis-got) - Convenience wrapper for interacting with the Travis API
324
325
326## Created by
327
328[![Sindre Sorhus](https://avatars.githubusercontent.com/u/170270?v=3&s=100)](https://sindresorhus.com) | [![Vsevolod Strukchinsky](https://avatars.githubusercontent.com/u/365089?v=3&s=100)](https://github.com/floatdrop)
329---|---
330[Sindre Sorhus](https://sindresorhus.com) | [Vsevolod Strukchinsky](https://github.com/floatdrop)
331
332
333## License
334
335MIT © [Sindre Sorhus](https://sindresorhus.com)
336