简体   繁体   English

如何在 Deno 中使用流?

[英]How to use streams in Deno?

I am very confused on Deno documentation.我对 Deno 文档感到非常困惑。 It has ReadableStream and WritableStream API, but it doesn't have a documentation to use it.它有ReadableStreamWritableStream API,但没有使用它的文档。

I want to read from ReadableStream and write to WritableStream , how can I do that in Deno?我想从ReadableStream读取并写入WritableStream ,我该如何在 Deno 中做到这一点?

I want to read from ReadableStream and write to WritableStream , how can I do that in Deno?我想从ReadableStream读取并写入WritableStream ,我该如何在 Deno 中做到这一点?

Here's a basic TypeScript example demonstrating manual use of the readable and writable parts of a TextEncoderStream (which is a subtype of TransformStream ) with verbose console logging:这是一个基本的 TypeScript 示例,演示了手动使用带有详细控制台日志记录的TextEncoderStream (它是TransformStream的子类型)的readablewritable部分:

so-73087438.ts : so-73087438.ts

const decoder = new TextDecoder();
const decode = (chunk: Uint8Array): string =>
  decoder.decode(chunk, { stream: true });

const stream = new TextEncoderStream();

(async () => {
  for await (const chunk of stream.readable) {
    const message = `Chunk read from stream: "${decode(chunk)}"`;
    console.log(message);
  }
  console.log("Stream closed");
})();

const texts = ["hello", "world"];

const writer = stream.writable.getWriter();
const write = async (chunk: string): Promise<void> => {
  await writer.ready;
  await writer.write(chunk);
};

for (const str of texts) {
  const message = `Writing chunk to stream: "${str}"`;
  console.log(message);
  await write(str);
}

console.log("Releasing lock on stream writer");
writer.releaseLock();
console.log("Closing stream");
await stream.writable.close();

% deno --version
deno 1.24.0 (release, x86_64-apple-darwin)
v8 10.4.132.20
typescript 4.7.4

% deno run so-73087438.ts
Writing chunk to stream: "hello"
Chunk read from stream: "hello"
Writing chunk to stream: "world"
Chunk read from stream: "world"
Releasing lock on stream writer
Closing stream
Stream closed


Covering the entirety of the API for WHATWG Streams is out of scope for a Stack Overflow answer.涵盖WHATWG Streams的整个 API 超出了 Stack Overflow 答案的范围。 The following links will answer any question you could ask about these streams:以下链接将回答您可能对这些流提出的任何问题:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM