duplex([options])
新增于: v25.9.0
创建一对连接的双工通道以实现双向通信,类似于 socketpair()。写入一个通道的写入端的数据会出现在另一个通道的可读端。
🌐 Create a pair of connected duplex channels for bidirectional communication,
similar to socketpair(). Data written to one channel's writer appears in
the other channel's readable.
每个通道都有:
🌐 Each channel has:
writer— 一个用于向节点发送数据的 [Writer 接口][] 对象。readable— 一个用于从对等方读取数据的AsyncIterable<Uint8Array[]>。close()— 关闭该端的通道(幂等)。[Symbol.asyncDispose]()— 为await using提供异步释放支持。
import { duplex, text } from 'node:stream/iter'; const [client, server] = duplex(); // Server echoes back const serving = (async () => { for await (const chunks of server.readable) { await server.writer.writev(chunks); } })(); await client.writer.write('hello'); await client.writer.end(); console.log(await text(server.readable)); // handled by echo await serving;const { duplex, text } = require('node:stream/iter'); async function run() { const [client, server] = duplex(); // Server echoes back const serving = (async () => { for await (const chunks of server.readable) { await server.writer.writev(chunks); } })(); await client.writer.write('hello'); await client.writer.end(); console.log(await text(server.readable)); // handled by echo await serving; } run().catch(console.error);