-
Notifications
You must be signed in to change notification settings - Fork 16
/
disk_cache.ts
42 lines (36 loc) · 1.2 KB
/
disk_cache.ts
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
// Copyright 2018-2024 the Deno authors. MIT license.
import { ensureDir } from "@std/fs/ensure-dir";
import { dirname, isAbsolute, join } from "@std/path";
import { readAll, writeAll } from "@std/io";
import { assert, CACHE_PERM } from "./util.ts";
import { instantiate } from "./lib/deno_cache_dir.generated.js";
export class DiskCache {
location: string;
constructor(location: string) {
assert(isAbsolute(location));
this.location = location;
}
async get(filename: string): Promise<Uint8Array> {
const path = join(this.location, filename);
const file = await Deno.open(path, { read: true });
const value = await readAll(file);
file.close();
return value;
}
async set(filename: string, data: Uint8Array): Promise<void> {
const path = join(this.location, filename);
const parentFilename = dirname(path);
await ensureDir(parentFilename);
const file = await Deno.open(path, {
write: true,
create: true,
mode: CACHE_PERM,
});
await writeAll(file, data);
file.close();
}
static async getCacheFilename(url: URL): Promise<string> {
const { url_to_filename } = await instantiate();
return url_to_filename(url.toString());
}
}