Open History to see the last commit
1import type { File } from "expo-file-system";
2
3let tempFileSequence = 0;
4
5/**
6 * Each write stages through its own temp file so concurrent writers to the same
7 * destination cannot move or clobber each other's staging file mid-flight.
8 * A failed write must clean up its own staging file so retries do not leak it.
9 */
10export async function writeFileAtomically(file: File, contents: string): Promise<void> {
11 const { File: FileConstructor } = await import("expo-file-system");
12 tempFileSequence += 1;
13 const temp = new FileConstructor(file.parentDirectory, `${file.name}.${tempFileSequence}.tmp`);
14 try {
15 temp.create({ intermediates: true, overwrite: true });
16 await temp.write(contents);
17 temp.moveSync(file, { overwrite: true });
18 } catch (error) {
19 try {
20 if (temp.exists) temp.delete();
21 } catch {
22 // Preserve the original write failure even if best-effort cleanup fails.
23 }
24 throw error;
25 }
26}