-
-
Notifications
You must be signed in to change notification settings - Fork 917
/
get-body-size.ts
43 lines (33 loc) 路 847 Bytes
/
get-body-size.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import {ReadStream, stat} from 'fs';
import {promisify} from 'util';
import {ClientRequestArgs} from 'http';
import is from '@sindresorhus/is';
import isFormData from './is-form-data';
interface Options {
body?: unknown;
headers: ClientRequestArgs['headers'];
}
const statAsync = promisify(stat);
export default async (options: Options): Promise<number | undefined> => {
const {body, headers} = options;
if (headers && 'content-length' in headers) {
return Number(headers['content-length']);
}
if (!body) {
return 0;
}
if (is.string(body)) {
return Buffer.byteLength(body);
}
if (is.buffer(body)) {
return body.length;
}
if (isFormData(body)) {
return promisify(body.getLength.bind(body))();
}
if (body instanceof ReadStream) {
const {size} = await statAsync(body.path);
return size;
}
return undefined;
};