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
40
41
42
43
44
45
46
47
48
49
|
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { pipeline } from 'node:stream/promises';
import fs from 'node:fs';
import * as tmp from 'tmp';
export function createTemp(): Promise<[string, () => void]> {
return new Promise<[string, () => void]>((res, rej) => {
tmp.file((e, path, fd, cleanup) => {
if (e) return rej(e);
res([path, process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'development' ? cleanup : () => {}]);
});
});
}
export function createTempDir(): Promise<[string, () => void]> {
return new Promise<[string, () => void]>((res, rej) => {
tmp.dir(
{
unsafeCleanup: true,
},
(e, path, cleanup) => {
if (e) return rej(e);
res([path, process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'development' ? cleanup : () => {}]);
},
);
});
}
export async function saveToTempFile(stream: NodeJS.ReadableStream & { truncated?: boolean }): Promise<[string, () => void]> {
const [filepath, cleanup] = await createTemp();
try {
await pipeline(stream, fs.createWriteStream(filepath));
} catch (e) {
cleanup();
throw e;
}
if (stream.truncated) {
cleanup();
throw new Error('Read failed: input stream truncated');
}
return [filepath, cleanup];
}
|