Skip to content

Commit 07e56ef

Browse files
committed
Add an example with ReadableStream.
1 parent d1f83b2 commit 07e56ef

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

readme.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,45 @@ const options = {
105105
await fetch("https://httpbin.org/post", options)
106106
```
107107

108+
4. In this example we will pull FormData content into the ReadableStream:
109+
110+
```js
111+
// This module is only necessary when you targeting Node.js or need web streams that implement Symbol.asyncIterator
112+
import {ReadableStream} from "web-streams-api/ponyfill/es2018"
113+
114+
import {Encoder} from "form-data-encoder"
115+
import {FormData} from "formdata-node"
116+
117+
import fetch from "node-fetch"
118+
119+
const toReadableStream = iterable => new ReadableStream({
120+
async pull(controller) {
121+
const {value, done} = await iterable.next()
122+
123+
if (done) {
124+
return controller.close()
125+
}
126+
127+
controller.enqueue(value)
128+
}
129+
})
130+
131+
const fd = new FormData()
132+
133+
fd.set("field", "My hovercraft is full of eels")
134+
135+
const encoder = new Encoder(fd)
136+
137+
const options = {
138+
method: "post",
139+
headers: encoder.headers,
140+
body: toReadableStream(encoder.encode())
141+
}
142+
143+
// Note that this example requires `fetch` to support Symbol.asyncIterator, which node-fetch lacks of (but will support eventually)
144+
await fetch("https://httpbin.org/post", options)
145+
```
146+
108147
# Installation
109148

110149
You can install this package using npm:

0 commit comments

Comments
 (0)