fs writeFile wx Flag Exclusive Create
Write with flag 'wx' so an existing path fails with EEXIST instead of truncating, the one-time init and lockfile pattern.
Code
// flag 'wx' = exclusive create: the write fails when the path already
// exists, so init files and lockfiles keep a single owner
import { writeFile, readFile } from 'node:fs/promises';
import { join } from 'node:path';
const target = join(process.cwd(), 'bootstrap.lock');
await writeFile(target, 'owner=build-42\n', { flag: 'wx' });
const first = await readFile(target, 'utf8');
console.log('first write created:', first.trim());
try {
await writeFile(target, 'owner=build-43\n', { flag: 'wx' });
console.log('second write unexpectedly succeeded');
} catch (err) {
console.log('second write rejected with:', err.code);
}
// the default 'w' flag truncates instead of failing
await writeFile(target, 'owner=build-43\n');
const overwritten = await readFile(target, 'utf8');
console.log('plain write overwrote:', overwritten.trim());Output
Captured from a sandboxed run of this snippet in the build pipeline.
first write created: owner=build-42
second write rejected with: EEXIST
plain write overwrote: owner=build-43How the snippet works
Every asynchronous step is awaited, so rejections surface where the call happens. The import names the platform contact area: writeFile, readFile, join, all from node:fs/promises, node:path.
Top-level bindings target, first, overwritten hold the demo state — nothing sits inside a function scope.
Points of care
- The only import,
node:fs/promises, is part of the Node.js standard library.
Using it
Output lines are prefixed (first write created:, second write rejected with:, plain write overwrote:), making each step’s effect easy to spot.
Key statements
await writeFile(target, 'owner=build-42\n', { flag: 'wx' });
await writeFile(target, 'owner=build-43\n', { flag: 'wx' });
const overwritten = await readFile(target, 'utf8');
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The imports resolve to Node.js core modules, which the runtime provides.
Report a problem with this exampleOpens a pre-filled issue on GitHub.