forked from node-formidable/formidable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultipart-parser.js
37 lines (30 loc) · 1015 Bytes
/
multipart-parser.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
import { Blob } from 'node:buffer';
import { Readable } from 'node:stream';
import { FormData, formDataToBlob } from 'formdata-polyfill/esm.min.js'
import { MultipartParser } from '../src/index.js';
const blob1 = new Blob(
['Content of a.txt.'],
{ type: 'text/plain' }
);
const blob2 = new Blob(
['<!DOCTYPE html><title>Content of a.html.</title>'],
{ type: 'text/html' }
);
const fd = new FormData();
fd.set('text', 'some text ...');
fd.set('z', 'text inside z');
fd.set('file1', blob1, 'a.txt');
fd.set('file2', blob2, 'a.html');
const multipartParser = new MultipartParser();
multipartParser.on('data', ({ name, buffer, start, end }) => {
console.log(`${name}:`);
if (buffer && start && end) {
console.log(String(buffer.slice(start, end)));
}
console.log();
});
multipartParser.on('error', console.error);
const blob = formDataToBlob(fd);
const boundary = blob.type.split('boundary=')[1];
multipartParser.initWithBoundary(boundary);
Readable.from(blob.stream()).pipe(multipartParser);