toWritable(writer)


稳定性: 1 - 实验性

  • writer <Object> 一个流/迭代写入器。仅需要 write() 方法;end()、fail()、writeSync()、writevSync()、endSync() 和 writev() 是可选的。
  • 返回:<stream.Writable>

创建一个由流/迭代 Writer 支持的经典 stream.Writable。

🌐 Creates a classic stream.Writable backed by a stream/iter Writer.

每个 _write() / _writev() 调用都会先尝试 Writer 的同步方法(writeSync / writevSync),如果同步路径返回 false 就会回退到异步方法。类似地,_final() 会先尝试 endSync() 再到 end()。当同步路径成功时,回调会通过 queueMicrotask 延迟处理,以保持异步解析的约定。

🌐 Each _write() / _writev() call attempts the Writer's synchronous method first (writeSync / writevSync), falling back to the async method if the sync path returns false. Similarly, _final() tries endSync() before end(). When the sync path succeeds, the callback is deferred via queueMicrotask to preserve the async resolution contract.

经典的流回调不能将任意值表示为错误。一个非 Error 类型的原因会在传给回调之前被封装在 ERR_FALSY_VALUE_REJECTION 或 ERR_OPERATION_FAILED 错误中。错误的 reason 属性包含原始值。

🌐 Classic stream callbacks cannot represent arbitrary values as errors. A non-Error reason is wrapped in an ERR_FALSY_VALUE_REJECTION or ERR_OPERATION_FAILED error before it is passed to the callback. The error's reason property contains the original value.

在成功完成之前销毁可写对象会调用 writer.fail()。如果 fail() 不可用,则在 Writer 实现时使用 Symbol.dispose 或 Symbol.asyncDispose。

🌐 Destroying the Writable before successful completion calls writer.fail(). If fail() is unavailable, Symbol.dispose or Symbol.asyncDispose is used when implemented by the Writer.

Writable 使用默认的经典流 highWaterMark。经典流的背压会限制等待写入到底层 Writer 的数据,而 Writer 控制活动的 _write() 或 _writev() 操作的完成。

🌐 The Writable uses the default classic stream highWaterMark. Classic stream backpressure bounds writes waiting to reach the underlying Writer, while the Writer controls completion of the active _write() or _writev() operation.

import { push, toWritable } from 'node:stream/iter';

const { writer, readable } = push();
const writable = toWritable(writer);

writable.write('hello');
writable.end();const { push, toWritable } = require('node:stream/iter');

const { writer, readable } = push();
const writable = toWritable(writer);

writable.write('hello');
writable.end();