D
Deno

help

How can I replace writeAllSync with the Streams API?

Aandrewthauer11/11/2023
How would one best refactor the following code to use the Web Streams API as suggested by the deprecated stdlib streams module? I was hoping to not have to change this to async for now. writeAllSync(Deno.stdout, this.encoder.encode(msg));
DAHDeno AI Helper11/11/2023
The Deno.writeAllSync function is deprecated and the documentation recommends using writeAllSync from std/streams/write_all.ts instead. However, you mentioned that you want to use the Web Streams API and keep the operation synchronous. Unfortunately, the Web Streams API is inherently asynchronous, and there isn't a direct synchronous equivalent in the API. This is because streams are designed to handle data that might not be immediately available, and to not block the main execution thread while waiting for data. If you want to use the Web Streams API, you would need to refactor your code to be asynchronous. Here's an example of how you could do that:
import { writerFromStreamWriter } from "https://deno.land/std/io/mod.ts";

const encoder = new TextEncoder();
const msg = "Hello, Deno! 🦕";

const writer = writerFromStreamWriter(Deno.stdout.writable.getWriter());
await Deno.writeAll(writer, encoder.encode(msg));
import { writerFromStreamWriter } from "https://deno.land/std/io/mod.ts";

const encoder = new TextEncoder();
const msg = "Hello, Deno! 🦕";

const writer = writerFromStreamWriter(Deno.stdout.writable.getWriter());
await Deno.writeAll(writer, encoder.encode(msg));
In this example, writerFromStreamWriter is used to create a Deno writer from the WritableStream returned by Deno.stdout.writable. Then, Deno.writeAll is used to write the encoded message to the writer. Note that this code is asynchronous and needs to be used in an async function or with a top-level await. If you need to keep your code synchronous, you might want to stick with Deno.writeAllSync until it's removed, or refactor your code to support asynchronous operations.

Looking for more? Join the community!