KITFORMA · EDITORIAL ANSWER
Why is checking fs.exists before opening a file unreliable?
KitForma editorial guide. Attempt file creation with the exclusive wx flag and handle EEXIST instead of checking existence and then writing.
Step-by-step answer
import { mkdtemp, open, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const directory = await mkdtemp(join(tmpdir(), "kitforma-exclusive-"));
const path = join(directory, "result.txt");
async function createOnce(label) {
let handle;
try {
handle = await open(path, "wx");
} catch (error) {
if (error.code === "EEXIST") return false;
throw error;
}
try { await handle.writeFile(label, "utf8"); }
finally { await handle.close(); }
return true;
}
try {
const outcomes = await Promise.all([createOnce("first"), createOnce("second")]);
console.log("created:", outcomes.filter(Boolean).length);
console.log("conflicts:", outcomes.filter(value => !value).length);
console.log("complete content:", ["first", "second"].includes(await readFile(path, "utf8")));
} finally {
await rm(directory, { recursive: true, force: true });
}created: 1
conflicts: 1
complete content: trueSources and verification
Sources checked:
This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.