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

atomic-file.ts

20 lines691 Bytes

1import type { File } from "expo-file-system";
2​
3let tempFileSequence = 0;
4​
5/** Use distinct staging files for concurrent writes and remove them on failure. */
6export async function writeFileAtomically(file: File, contents: string): Promise<void> {
7 const { File: FileConstructor } = await import("expo-file-system");
8 tempFileSequence += 1;
9 const temp = new FileConstructor(file.parentDirectory, `${file.name}.${tempFileSequence}.tmp`);
10 try {
11 temp.create({ intermediates: true, overwrite: true });
12 await temp.write(contents);
13 temp.moveSync(file, { overwrite: true });
14 } catch (error) {
15 try {
16 if (temp.exists) temp.delete();
17 } catch {}
18 throw error;
19 }