fromWritable(writable[, options])


稳定性: 1 - 实验性

  • writable <stream.Writable> | <Object> 一个经典的可写流,或者一个拥有 write()、end()、destroy()、on() 和 removeListener() 方法的兼容对象。
  • options <Object>
    • backpressure <string> 背压策略。默认值: 'strict'。
      • 'strict' —— 当缓冲区已满时,一次写入可能需要等待。之后的写入将被拒绝,直到它被接受或取消。
      • 'unbounded' —— 当缓冲区已满时,写入会排队。推荐与 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.

由于在经典可写对象上的所有写操作本质上都是异步的, 同步的 Writer 方法(writeSync、writevSync、endSync)总是返回 false 或 -1, 并依赖异步路径。 排队的 write() 或 writev() 可以在到达经典可写对象之前用它的 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. A queued write() or writev() can be canceled with its options.signal before it reaches the classic Writable.

如果 writer.fail(reason) 收到一个非错误原因,经典 Writable 会被 ERR_FALSY_VALUE_REJECTION 或 ERR_OPERATION_FAILED 销毁。它的 reason 属性包含原始值,该值仍然是 Writer 存储的失败原因。

🌐 If writer.fail(reason) receives a non-Error reason, the classic Writable is destroyed with an ERR_FALSY_VALUE_REJECTION or ERR_OPERATION_FAILED error. Its reason property contains the original value, which remains the Writer's stored failure reason.

结果会根据每个实例和背压策略进行缓存——对相同的流和 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.

对于不暴露 writableHighWaterMark、writableLength 或类似属性的动态类型流,将使用合理的默认值。可检测的对象模式可写流将被拒绝,因为 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: 'unbounded' }));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: 'unbounded' }));
}
run();