fromWritable(writable[, options])


稳定性: 1 - 实验性

  • writable <stream.Writable> | <Object> 一个经典的可写流或任何具有 write()on() 方法的对象。
  • options <Object>
    • backpressure <string> 背压策略。默认值: 'strict'
      • 'strict' -- 当缓冲区已满时写入会被拒绝。用于捕获忽略背压的调用者。
      • 'block' -- 当缓冲区已满时会写入等待排空。建议与 pipeTo() 一起使用。
      • 'drop-newest' -- 当缓冲区已满时,写入会被悄无声息地丢弃。
      • 'drop-oldest' -- 不支持。会抛出 ERR_INVALID_ARG_VALUE
  • 返回:<Object> 一个流/迭代器写入器适配器。

从经典的 Writable 流(或动态类型的等效对象)创建一个流/迭代 Writer 适配器。该适配器可以作为目标传递给 pipeTo()

🌐 Creates a stream/iter Writer adapter from a classic Writable stream (or duck-typed equivalent). The adapter can be passed to pipeTo() as a destination.

由于经典 Writable 上的所有写入本质上是异步的, 同步 Writer 方法(writeSyncwritevSyncendSync)总是返回 false-1, 转而使用异步路径。 Writer 接口中的每次写入 options.signal 参数也会被忽略。

🌐 Since all writes on a classic Writable are fundamentally asynchronous, the synchronous Writer methods (writeSync, writevSync, endSync) always return false or -1, deferring to the async path. The per-write options.signal parameter from the Writer interface is also ignored.

结果会根据每个实例和背压策略进行缓存——对相同的流和 backpressure 选项调用 fromWritable() 两次会返回相同的 Writer。

🌐 The result is cached per instance and backpressure policy -- calling fromWritable() twice with the same stream and backpressure option returns the same Writer.

对于不暴露 writableHighWaterMarkwritableLength 或类似属性的动态类型流,将使用合理的默认值。可检测的对象模式可写流将被拒绝,因为 Writer 接口仅支持字节。

🌐 For duck-typed streams that do not expose writableHighWaterMark, writableLength, or similar properties, sensible defaults are used. Object-mode writables (if detectable) are rejected since the Writer interface is bytes-only.

import { Writable } from 'node:stream';
import { from, fromWritable, pipeTo } from 'node:stream/iter';

const writable = new Writable({
  write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
});

await pipeTo(from('hello world'),
             fromWritable(writable, { backpressure: 'block' }));const { Writable } = require('node:stream');
const { from, fromWritable, pipeTo } = require('node:stream/iter');

async function run() {
  const writable = new Writable({
    write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
  });

  await pipeTo(from('hello world'),
               fromWritable(writable, { backpressure: 'block' }));
}
run();