-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstream-tools.js
66 lines (53 loc) · 1.39 KB
/
stream-tools.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
export function stringToTextStream(value){
return new ReadableStream({
start(controller){
controller.enqueue(value);
controller.close();
}
});
}
export function stringToBinaryStream(value){
return stringToTextStream(value).pipeThrough(new TextEncoderStream());
}
export async function textStreamToString(stream){
const reader = stream.getReader();
let text = "";
let done = false;
while(!done){
const result = await reader.read();
done = result.done;
if(result.value){
text += result.value;
}
}
return text;
}
export async function binaryStreamToString(stream){
return await textStreamToString(stream.pipeThrough(new TextDecoderStream()));
}
export function objectToBinaryJsonStream(value){
return stringToBinaryStream(JSON.stringify(value));
}
export async function binaryJsonStreamToObject(stream){
return JSON.parse(binaryStreamToString(stream));
}
export async function binaryStreamToArrayBuffer(stream){
const reader = stream.getReader();
const chunks = [];
let done = false;
while (!done) {
const result = await reader.read();
done = result.done;
if (result.value) {
chunks.push(result.value);
}
}
const totalByteLength = chunks.map(b => b.byteLength).reduce((sum, val) => sum + val);
const buffer = new Uint8Array(totalByteLength);
let i = 0;
for(const chunk of chunks){
buffer.set(chunk, i);
i += chunk.byteLength;
}
return buffer.buffer;
}