Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

atomic-file.ts

16 lines654 Bytes

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 */
9export async function writeFileAtomically(file: File, contents: string): Promise<void> {
10 const { File: FileConstructor } = await import("expo-file-system");
11 tempFileSequence += 1;
12 const temp = new FileConstructor(file.parentDirectory, `${file.name}.${tempFileSequence}.tmp`);
13 temp.create({ intermediates: true, overwrite: true });
14 await temp.write(contents);
15 temp.moveSync(file, { overwrite: true });