Skip to content

Commit 6cc3d9f

Browse files
Use responseType instead of options.encoding to get a Buffer (sindresorhus#940)
Co-authored-by: Sindre Sorhus <[email protected]>
1 parent 3acdb69 commit 6cc3d9f

8 files changed

+38
-19
lines changed

readme.md

+13-7
Original file line numberDiff line numberDiff line change
@@ -248,17 +248,21 @@ Default: `'default'`
248248

249249
Parsing method used to retrieve the body from the response.
250250

251-
- `'default'` - if `options.encoding` is `null`, the body will be a Buffer. Otherwise it will be a string unless it's overwritten in a `afterResponse` hook,
252-
- `'text'` - will always give a string, no matter what's the `options.encoding` or if the body is a custom object,
253-
- `'json'` - will always give an object, unless it's invalid JSON - then it will throw.
254-
- `'buffer'` - will always give a Buffer, no matter what's the `options.encoding`. It will throw if the body is a custom object.
251+
- `'default'` - Will give a string unless the body is overwritten in a `afterResponse` hook or if `options.decompress` is set to false - Will give a Buffer if the response is compresssed.
252+
- `'text'` - Will give a string no matter what.
253+
- `'json'` - Will give an object, unless the body is invalid JSON, then it will throw.
254+
- `'buffer'` - Will give a Buffer, ignoring `options.encoding`. It will throw if the body is a custom object.
255255

256-
The promise has `.json()` and `.buffer()` and `.text()` functions which set this option automatically.
256+
The promise has `.json()` and `.buffer()` and `.text()` methods which set this option automatically.
257257

258258
Example:
259259

260260
```js
261+
// This
261262
const body = await got(url).json();
263+
264+
// is the same as this
265+
const body = await got(url, {responseType: 'json'});
262266
```
263267

264268
###### resolveBodyOnly
@@ -297,10 +301,12 @@ Ignore invalid cookies instead of throwing an error. Only useful when the `cooki
297301

298302
###### encoding
299303

300-
Type: `string | null`<br>
304+
Type: `string`<br>
301305
Default: `'utf8'`
302306

303-
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. If `null`, the body is returned as a [`Buffer`](https://nodejs.org/api/buffer.html) (binary data).
307+
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data.
308+
309+
To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set [`responseType`](#responseType) to `buffer` instead.
304310

305311
###### form
306312

source/as-promise.ts

+1-3
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,8 @@ export default function asPromise(options: NormalizedOptions) {
5353
emitter.on('response', async (response: Response) => {
5454
proxy.emit('response', response);
5555

56-
const streamAsPromise = is.null_(options.encoding) ? getStream.buffer(response) : getStream(response, {encoding: options.encoding});
57-
5856
try {
59-
response.body = await streamAsPromise;
57+
response.body = await getStream(response, {encoding: options.encoding});
6058
} catch (error) {
6159
emitError(new ReadError(error, options));
6260
return;

source/get-response.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@ export default async (response: IncomingMessage, options: NormalizedOptions, emi
2121
) as Response;
2222

2323
if (!options.decompress && ['gzip', 'deflate', 'br'].includes(response.headers['content-encoding'] ?? '')) {
24-
options.encoding = null;
24+
options.responseType = 'default';
25+
26+
// @ts-ignore Internal use.
27+
options.encoding = 'buffer';
2528
}
2629

2730
emitter.emit('response', newResponse);

source/normalize-arguments.ts

+5
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,11 @@ export const preNormalizeArguments = (options: Options, defaults?: NormalizedOpt
164164
options.cookieJar = {setCookie, getCookieString};
165165
}
166166

167+
// `options.encoding`
168+
if (is.null_(options.encoding)) {
169+
throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');
170+
}
171+
167172
return options as NormalizedOptions;
168173
};
169174

source/utils/types.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ export interface Options extends URLOptions {
131131
hooks?: Partial<Hooks>;
132132
decompress?: boolean;
133133
isStream?: boolean;
134-
encoding?: BufferEncoding | null;
134+
encoding?: BufferEncoding;
135135
method?: Method;
136136
retry?: number | RetryOptions;
137137
throwHttpErrors?: boolean;

test/arguments.ts

+6
Original file line numberDiff line numberDiff line change
@@ -336,3 +336,9 @@ test('`context` option is accessible when extending instances', t => {
336336
t.is(instance.defaults.options.context, context);
337337
t.false({}.propertyIsEnumerable.call(instance.defaults.options, 'context'));
338338
});
339+
340+
test('throws if `options.encoding` is `null`', async t => {
341+
await t.throwsAsync(got('https://example.com', {
342+
encoding: null
343+
}), 'To get a Buffer, set `options.responseType` to `buffer` instead');
344+
});

test/http.ts

+6-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import is from '@sindresorhus/is';
21
import test from 'ava';
32
import got from '../source';
43
import withServer from './helpers/with-server';
@@ -72,13 +71,15 @@ test('invalid protocol throws', async t => {
7271
});
7372
});
7473

75-
test('gives buffer if `options.encoding` is null', withServer, async (t, server, got) => {
74+
test('custom `options.encoding`', withServer, async (t, server, got) => {
75+
const string = 'ok';
76+
7677
server.get('/', (_request, response) => {
77-
response.end('ok');
78+
response.end(string);
7879
});
7980

80-
const data = (await got({encoding: null})).body;
81-
t.true(is.buffer(data));
81+
const data = (await got({encoding: 'base64'})).body;
82+
t.is(data, Buffer.from(string).toString('base64'));
8283
});
8384

8485
test('`searchParams` option', withServer, async (t, server, got) => {

test/progress.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ test('download progress', withServer, async (t, server, got) => {
7171

7272
const events = [];
7373

74-
const {body} = await got({encoding: null})
74+
const {body} = await got({responseType: 'buffer'})
7575
.on('downloadProgress', event => events.push(event));
7676

7777
checkEvents(t, events, body.length);
@@ -92,7 +92,7 @@ test('download progress - stream', withServer, async (t, server, got) => {
9292

9393
const events = [];
9494

95-
const stream = got.stream({encoding: null})
95+
const stream = got.stream({responseType: 'buffer'})
9696
.on('downloadProgress', event => events.push(event));
9797

9898
await getStream(stream);

0 commit comments

Comments
 (0)