forked from facebook/metro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileStore.js
102 lines (85 loc) 路 2.17 KB
/
FileStore.js
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const fs = require('fs');
const path = require('path');
const rimraf = require('rimraf');
const NULL_BYTE = 0x00;
const NULL_BYTE_BUFFER = Buffer.from([NULL_BYTE]);
export type Options = {|
root: string,
|};
class FileStore<T> {
_root: string;
constructor(options: Options) {
this._root = options.root;
this._createDirs();
}
async get(key: Buffer): Promise<?T> {
try {
const data = await fs.promises.readFile(this._getFilePath(key));
if (data[0] === NULL_BYTE) {
return (data.slice(1): any);
}
return JSON.parse(data.toString('utf8'));
} catch (err) {
if (err.code === 'ENOENT' || err instanceof SyntaxError) {
return null;
}
throw err;
}
}
async set(key: Buffer, value: T): Promise<void> {
const filePath = this._getFilePath(key);
try {
await this._set(filePath, value);
} catch (err) {
if (err.code === 'ENOENT') {
fs.mkdirSync(path.dirname(filePath), {recursive: true});
await this._set(filePath, value);
} else {
throw err;
}
}
}
async _set(filePath: string, value: T): Promise<void> {
let content;
if (value instanceof Buffer) {
content = Buffer.concat([NULL_BYTE_BUFFER, value]);
} else {
content = JSON.stringify(value) ?? JSON.stringify(null);
}
await fs.promises.writeFile(filePath, content);
}
clear() {
this._removeDirs();
this._createDirs();
}
_getFilePath(key: Buffer): string {
return path.join(
this._root,
key.slice(0, 1).toString('hex'),
key.slice(1).toString('hex'),
);
}
_createDirs() {
for (let i = 0; i < 256; i++) {
fs.mkdirSync(path.join(this._root, ('0' + i.toString(16)).slice(-2)), {
recursive: true,
});
}
}
_removeDirs() {
for (let i = 0; i < 256; i++) {
rimraf.sync(path.join(this._root, ('0' + i.toString(16)).slice(-2)));
}
}
}
module.exports = FileStore;