forked from node-fetch/node-fetch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
form-data.js
82 lines (64 loc) · 1.61 KB
/
form-data.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import {randomBytes} from 'crypto';
import {isBlob} from './is.js';
const carriage = '\r\n';
const dashes = '-'.repeat(2);
const carriageLength = Buffer.byteLength(carriage);
/**
* @param {string} boundary
*/
const getFooter = boundary => `${dashes}${boundary}${dashes}${carriage.repeat(2)}`;
/**
* @param {string} boundary
* @param {string} name
* @param {*} field
*
* @return {string}
*/
function getHeader(boundary, name, field) {
let header = '';
header += `${dashes}${boundary}${carriage}`;
header += `Content-Disposition: form-data; name="${name}"`;
if (isBlob(field)) {
header += `; filename="${field.name}"${carriage}`;
header += `Content-Type: ${field.type || 'application/octet-stream'}`;
}
return `${header}${carriage.repeat(2)}`;
}
/**
* @return {string}
*/
export const getBoundary = () => randomBytes(8).toString('hex');
/**
* @param {FormData} form
* @param {string} boundary
*/
export async function * formDataIterator(form, boundary) {
for (const [name, value] of form) {
yield getHeader(boundary, name, value);
if (isBlob(value)) {
yield * value.stream();
} else {
yield value;
}
yield carriage;
}
yield getFooter(boundary);
}
/**
* @param {FormData} form
* @param {string} boundary
*/
export function getFormDataLength(form, boundary) {
let length = 0;
for (const [name, value] of form) {
length += Buffer.byteLength(getHeader(boundary, name, value));
if (isBlob(value)) {
length += value.size;
} else {
length += Buffer.byteLength(String(value));
}
length += carriageLength;
}
length += Buffer.byteLength(getFooter(boundary));
return length;
}