-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtempFiles.ts
More file actions
39 lines (35 loc) · 1.35 KB
/
tempFiles.ts
File metadata and controls
39 lines (35 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { mkdtempSync, writeFileSync } from "node:fs";
import { mkdtemp, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
/**
* Creates a temporary file with a custom filename, passes it to the callback function, and ensures cleanup
* @param filename The filename to use for the temporary file
* @param callback Function that receives the path to the temporary file
* @param content Optional content to write to the file
* @returns Whatever the callback returns
*/
export async function withTempFile<T>(
filename: string,
callback: (filePath: string) => Promise<T>,
content: string | Buffer = ""
): Promise<T> {
// Create temporary directory with random suffix
const tempDir = await mkdtemp(join(tmpdir(), "app-"));
const tempFile = join(tempDir, filename);
try {
// Write to the temporary file with appropriate permissions
await writeFile(tempFile, content, { mode: 0o600 });
// Use the file
return await callback(tempFile);
} finally {
// Clean up
await rm(tempDir, { recursive: true, force: true });
}
}
export function createTempFileSync(filename: string, content: string | Buffer = ""): string {
const tempDir = mkdtempSync(join(tmpdir(), "app-"));
const tempFile = join(tempDir, filename);
writeFileSync(tempFile, content, { mode: 0o600 });
return tempFile;
}