writeFileAtomic
writeFileAtomic(
filePath,data,options?):Promise<void>
Defined in: packages/node/src/fs/write-file-atomic.ts:105
Replaces a file’s contents in one step: a reader sees either the previous contents or the new ones, never a partial write.
The data goes to a uniquely named temporary file beside the destination,
which is then renamed over it. rename replaces the destination
atomically, so no window exists in which the path is missing.
Appending is rejected — flag: "a" and O_APPEND throw. Staging an append
means copying the destination into the temporary file and appending there,
which silently discards whatever another process wrote in between: the
opposite of what an appender expects. Read, concatenate and replace instead,
serialising the writers yourself when there is more than one:
const current = await readFile(path, "utf8").catch(() => "");await writeFileAtomic(path, `${current}${line}\n`);When the destination already exists its permission bits carry over, unless
options.mode says otherwise. Ownership does not: the replacement belongs to
the calling user.
Durability is a separate concern from atomicity — pass flush: true to fsync
the data before the rename. The parent directory is never fsynced, so the
rename itself may still be lost to a power failure.
Parameters
Section titled “Parameters”filePath
Section titled “filePath”PathLike
The path to replace.
string | ArrayBufferView<ArrayBufferLike> | Iterable<string | ArrayBufferView<ArrayBufferLike>, any, any> | AsyncIterable<string | ArrayBufferView<ArrayBufferLike>, any, any>
The contents to write.
options?
Section titled “options?”Encoding, mode, flag, flush and abort signal, as for
fs.writeFile. flag may only select exclusive creation ("wx",
O_EXCL); appending throws.
encoding?
Section titled “encoding?”BufferEncoding | null
OpenMode
flush?
Section titled “flush?”boolean
If all data is successfully written to the file, and flush
is true, filehandle.sync() is used to flush the data.
Default
falseMode
signal?
Section titled “signal?”AbortSignal | null
Returns
Section titled “Returns”Promise<void>
A promise that resolves once the destination holds the new contents.
Throws
Section titled “Throws”When options.flag requests an append.
Throws
Section titled “Throws”When the destination exists and options.flag is exclusive (code: "EEXIST"), or when any underlying syscall fails.