← Runtimes
Runtimes

I/O, buffering, and external state

Know when a write becomes visible outside your program.

Buffering separates accepting bytes in memory from completing I/O visible to another reader.

Outcome

Predict when written data becomes visible outside the program, flush at the points other readers depend on without giving up buffering, and keep several writers to one file from overwriting each other.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Buffer
Memory where a writer can collect bytes before passing them to its destination, possibly through several write calls.
Flush
Ask the writer to deliver pending bytes to its destination. A successful local-file buffer flush makes the bytes visible to fresh readers, without establishing power-loss durability.
File offset
The position used by an open file description. Separate opens normally have independent offsets; duplicated descriptors can share an offset.
Append mode
An open mode (O_APPEND) in which the kernel moves every write to the current end of the file.
Durability
Surviving a power loss. Successful file synchronization such as fsync is stronger than flushing a user-space buffer; filesystem and storage details matter.
Write stream
Node’s asynchronous file writer. Queueing a write and receiving completion are different events; filesystem work is not all executed as JavaScript on the event loop.

Bytes, buffers, and completion

File I/O changes state outside the program’s ordinary variables. A user-space buffer holds bytes in program memory before passing them to the destination. A buffered write can return after accepting text into that buffer; a large write or a full buffer can also send bytes immediately. Buffering does not promise that every write waits.

Completion belongs to a particular API boundary. Delivering buffered bytes, observing them through a fresh local-file reader and making them survive power loss are different claims. A flush requests delivery to the underlying writer; asynchronous writers also need their documented completion notification. Check the operation’s outcome before relying on its promised effect.

01When is it visible?

A completed write call is not a visible write

An event recorder must let a monitoring tool read all events at each progress check while keeping ordinary writes buffered. That works with one writer, but an audit writer opening the same log can overwrite earlier events. Where should the recorder publish buffered bytes, and how should both writers share the file?

The monitor reads the log at explicit progress checks, so each check is an observation point for the recorder.

Reduce one event to an 11-byte line and read the local file through a fresh observer before and after publishing the pending bytes. Assume file operations succeed. The TypeScript stream probe waits for asynchronous completion; the other writers expose an explicit flush.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { createWriteStream, existsSync, readFileSync, rmSync } from 'node:fs';

const path = '/tmp/visible.log';
const describe = () =>
  existsSync(path) ? `${readFileSync(path, 'utf8').length} bytes in the file` : 'no file yet';

rmSync(path, { force: true });
const stream = createWriteStream(path);
stream.write('first line\n');
console.log(`after write: ${describe()}`);

stream.end(() => {
  console.log(`after end: ${describe()}`);
});
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts
In the recorded runner setup, the program writes one 11-byte line through its writer, then reads the file fresh. What does the first read report?

02Two writers, one file

Separate opens have independent positions

Now add audit events without making either writer own the other’s buffer. Both writers can flush at the right checkpoint and still damage the log: separate opens of a path normally have independent offsets. This probe opens both handles before either write and deliberately uses truncating write mode, not append.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { closeSync, openSync, readFileSync, writeSync } from 'node:fs';

const path = '/tmp/shared.log';
const first = openSync(path, 'w');
const second = openSync(path, 'w');

writeSync(first, 'app: started\n');
writeSync(second, 'audit: ok\n');
closeSync(first);
closeSync(second);

console.log(JSON.stringify(readFileSync(path, 'utf8')));
Both handles open the same path for writing before either writes. The first writes "app: started\n" (13 bytes), then the second writes "audit: ok\n" (10 bytes). What does the file contain?

For a raw Node descriptor, openSync(path, "a") selects append instead of truncating write mode. The lab’s BufferedLog still decides when its pending bytes are sent.

03Practice

Record events other readers can trust

The recorder also needs a completion test after append mode resolves overwriting. Ordinary small writes can hide a buffer cleared too soon or published twice. The final task supplies a bounded-transfer adapter over real file writes so each call accepts only a small byte prefix. Its cap is authored test injection. Publishing a prefix and retiring pending bytes are separate responsibilities; the next checkpoint must see complete records without replaying already published bytes. The observer and Linux call counters stay separate from this injected transfer contract.

Buffer indexes count bytes. Advancing a JS string by a returned byte count can split or skip UTF-8 characters; the provided pending Buffer keeps the transfer unit explicit.

The event recorder

A recorder buffers events while an observer reads the local log at checkpoints. Record events, publish them at checks, then complete bounded transfers from both append writers without losing or replaying pending bytes.

  1. easy · R-BUF-V4-1 Record an event
  2. medium · R-BUF-V4-2 Visible at each check
  3. hard · R-BUF-V4-3 Publish every pending byte once
Check this idea later
A Go service logs many small lines through a default bufio.Writer on a local file and never calls Flush between requests. An operator runs tail -f on the log. What do they see?
On a local POSIX filesystem, two worker processes independently open the same report file with plain write mode and write their results. Some results are missing. What change prevents overwriting?
A program flushes its buffered writer, and immediately the machine loses power. Is the data guaranteed to be on disk?
Sources
In the frontend A response can acknowledge completed file I/O without proving durability. Optional

The recorder’s dashboard shows an event as saved after its POST succeeds. The server must finish the promised append before returning that acknowledgment; merely queueing a write and returning a response is too early. The persistence promise still needs to be stated separately.

app/api/events/route.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { appendFile } from 'node:fs/promises';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  const event = await request.json();
  await appendFile('/srv/events.log', JSON.stringify(event) + '\n');

  return new Response(null, { status: 204 });
}

This Node App Router handler awaits appendFile before returning 204. It acknowledges completion of that local file operation, not a successful fsync or power-loss test. Append behavior also does not make a multi-write logical event atomic with concurrent writers.

Sources: Node.js: appendFile,Next.js: Route Handlers,SvelteKit: server routes.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.