stream.writer


返回一个 Writer 对象,用于将数据分步推送到流中。Writer 实现了带有尝试同步-回退到异步模式的 stream/iter Writer 接口。

🌐 Returns a Writer object for pushing data to the stream incrementally. The Writer implements the stream/iter Writer interface with the try-sync-fallback-to-async pattern.

仅当在创建时或通过 stream.setBody() 未提供 body 源时可用。不可写的流会返回一个已关闭的 Writer。如果出站已配置,则抛出 ERR_INVALID_STATE。

🌐 Only available when no body source was provided at creation time or via stream.setBody(). Non-writable streams return an already-closed Writer. Throws ERR_INVALID_STATE if the outbound is already configured.

作者有以下方法:

🌐 The Writer has the following methods:

  • writeSync(chunk) — 同步写入。如果被接受返回 true,流量控制时返回 false。在 false 上不接受数据。
  • write(chunk[, options]) — 异步写入。当流受到流量控制而不是等待容量时会以 ERR_INVALID_STATE 拒绝。options.signal 在入口时会被检查,但在写入过程中不会被观察。
  • writevSync(chunks) — 同步向量写入。要么全部成功,要么全部失败。
  • writev(chunks[, options]) — 异步向量写。当流被流量控制而不是等待容量时,会拒绝并返回 ERR_INVALID_STATE。
  • endSync() — 同步关闭。返回总字节数或 -1。
  • end([options]) — 异步关闭。如果排水已在等待中,会在关闭前等待它完成。
  • fail(reason) — 出现流错误(将 RESET_STREAM 发送给对端)。当 reason 是 QuicError 时,其 error.errorCode 被用作生成的 RESET_STREAM 帧上的线编码;否则,线编码回退到协商的应用协议的“内部错误”代码(HTTP/3 为 H3_INTERNAL_ERROR (0x102),或原生 QUIC 为 QUIC 传输层的 INTERNAL_ERROR (0x1))。有关完全中止流的操作,并通过 STOP_SENDING 重置可读端的详情,请参见 stream.destroy()。
  • canWrite — 如果写入会被接受则为 true,如果已满则为 false,或者如果关闭/出错则为 null。当 writeSync() 返回 false 时,使用来自 node:stream/iter 的 ondrain() 在重试前等待。如果 ondrain() 返回 null,则没有等待排空的时间,写入不应重试。
import { ondrain } from 'node:stream/iter';

while (!writer.writeSync(chunk)) {
  const drain = ondrain(writer);
  if (drain === null) break;
  await drain;
} 

每个 writeSync() / writevSync() / write() / writev() 输入块的字节都会被复制到一个内部缓冲区,因此调用者的源缓冲区保持不变,并且可以在调用返回后立即重用或修改。希望确保源缓冲区在交出后不能被修改的调用者,可以在传递缓冲区之前自行调用 ArrayBuffer.prototype.transfer()。

🌐 The bytes from each writeSync() / writevSync() / write() / writev() input chunk are copied into an internal buffer, so the caller's source buffer is unchanged and may be reused or mutated immediately after the call returns. Callers that want to ensure a source buffer cannot be mutated after handing it off can call ArrayBuffer.prototype.transfer() themselves before passing the buffer.