Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Streams and readline

Node.js writable.cork() and uncork() methods

Reference for writable.cork() and uncork() in Node.js: buffer several small writes and flush them together with writev, and how to nest cork calls.

writable.cork() forces a writable stream to hold all written chunks in memory instead of passing them to the destination right away. writable.uncork() releases them. If the stream implements writev(), all corked chunks are delivered in a single call, which is much cheaper than many tiny writes to a socket or file.

A typical use is writing a header and a body together: cork, write both, then uncork on the next tick.

NODE
stream.cork();
stream.write("header\n");
stream.write("body\n");
process.nextTick(() => stream.uncork());

Try it

Node.js Batching with writev

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Nested cork calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
writable.cork(): void
writable.uncork(): void
writable.writableCorked: number
Name Description
cork() Increments the cork counter; while it is above zero, writes are buffered.
uncork() Decrements the counter; at zero the buffered chunks are flushed.
writableCorked The current counter value.

Returns: nothing.

Edge cases: every cork() needs its own uncork(). Forgetting one leaves data stuck in the buffer. Calling end() flushes a corked stream anyway.

Usage notes

  • If the writable defines only _write(), uncorking calls it once per chunk; the saving comes from implementing _writev() (as net.Socket and fs.WriteStream do).
  • Corking does not break backpressure: write() still returns false when highWaterMark is exceeded, and you cannot drain a corked stream.
  • Uncork in the same tick only after you have written everything; process.nextTick() is the usual place when the writes come from several functions.
  • For HTTP responses and sockets, cork-then-uncork reduces the number of TCP packets and syscalls.
  • A single string concatenation is often simpler than cork for two small chunks.