summaryrefslogtreecommitdiff
path: root/packages/backend/src/misc/FileWriterStream.ts
blob: 27c67cb5dfa758cace393a144f44a37971a328cc (plain)
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
/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import * as fs from 'node:fs/promises';
import { WritableStream } from 'node:stream/web';
import type { PathLike } from 'node:fs';

/**
 * `fs.createWriteStream()`相当のことを行う`WritableStream` (Web標準)
 */
export class FileWriterStream extends WritableStream<Uint8Array> {
	constructor(path: PathLike) {
		let file: fs.FileHandle | null = null;

		super({
			start: async () => {
				file = await fs.open(path, 'a');
			},
			write: async (chunk, controller) => {
				if (file === null) {
					controller.error();
					throw new Error();
				}

				await file.write(chunk);
			},
			close: async () => {
				await file?.close();
			},
			abort: async () => {
				await file?.close();
			},
		});
	}
}