Node.js
Create a file only when it does not already exist
Use writeFile with the wx flag to create a new file and fail if that path already exists. This expresses the exclusivity requirement in the file operation itself.
Worked example
Node.js example · save as example.mjs and run node example.mjs
import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
const path = join(directory, "new.txt");
await fs.writeFile(path, "first", {encoding: "utf8", flag: "wx"});
try {
await fs.writeFile(path, "second", {encoding: "utf8", flag: "wx"});
} catch (error) { console.log(error.code); }
console.log(await fs.readFile(path, "utf8"));
} finally {
await fs.rm(directory, {recursive: true, force: true});
}How it works
The first operation creates the file. The second requests the same exclusive creation and fails instead of replacing the original. This is safer than checking whether the path exists and then performing an ordinary overwriting write.
Limits and mistakes
Filesystem and network-filesystem semantics matter for stronger coordination guarantees. Exclusive creation is not a substitute for a complete locking protocol. Handle errors other than an existing file when adapting the catch block to production code.
Check the result
Expect EEXIST followed by first. Confirm the original contents remain unchanged and that the program reports an unexpected error instead of assuming every failure means a duplicate.
Sources
Reference documentation for the behavior used in this guide: