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.
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()}`);
});
npx tsc --noEmit --strict main.ts && node main.ts
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.
Check this idea later
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.
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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?