Created
July 22, 2023 18:26
Deno.serve() doesn't stream, part 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const wait = async (ms) => new Promise((r) => setTimeout(r, ms)); | |
fetch('https://localhost:8000', { | |
duplex: 'half', | |
method: 'post', | |
body: new ReadableStream({ | |
async start(controller) { | |
await wait(1000); | |
controller.enqueue('This '); | |
await wait(1000); | |
controller.enqueue('is '); | |
await wait(1000); | |
controller.enqueue('a '); | |
await wait(1000); | |
controller.enqueue('slow '); | |
await wait(1000); | |
controller.enqueue('request.'); | |
controller.close(); | |
}, | |
}).pipeThrough(new TextEncoderStream()) | |
}).then((r) => r.body.pipeThrough(new TextDecoderStream())).then((r) => r.pipeTo(new WritableStream({ | |
write(value) { | |
console.log(value); | |
}, | |
close() { | |
console.log('Stream closed.'); | |
} | |
}))).then(() => console.log('Done writing stream')).catch(console.warn); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ./deno run -A --unsafely-ignore-certificate-errors=localhost --unstable streamtest.js | |
let cert = Deno.readTextFileSync('certificate.pem'); | |
let key = Deno.readTextFileSync('certificate.key'); | |
let responseInit = { | |
duplex: 'half', | |
headers: { | |
'Content-Type': 'text/plain; charset=UTF-8', | |
'Cross-Origin-Opener-Policy': 'unsafe-none', | |
'Cross-Origin-Embedder-Policy': 'unsafe-none', | |
'Access-Control-Allow-Origin': '*', | |
'Access-Control-Allow-Private-Network': 'true', | |
'Access-Control-Allow-Headers': 'Access-Control-Request-Private-Network', | |
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET,HEAD,QUERY', | |
} | |
}; | |
let server = Deno.serve({ | |
cert, | |
key | |
}, async (request) => { | |
try { | |
if (request.method === 'OPTIONS') { | |
return new Response(null, responseInit); | |
} | |
if (request.method === 'POST') { | |
return new Response( | |
request.body.pipeThrough(new TextDecoderStream()) | |
.pipeThrough( | |
new TransformStream({ | |
transform(value, c) { | |
console.log(value); | |
c.enqueue(value.toUpperCase()); | |
}, | |
flush() { | |
console.log('flush'); | |
}, | |
}) | |
) | |
.pipeThrough(new TextEncoderStream()), responseInit | |
); | |
} | |
} catch (e) { | |
console.log(e); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
./deno run -A --unstable --unsafely-ignore-certificate-errors=localhost client.js