-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path8.4-virtual-filesystem.js
70 lines (60 loc) · 1.57 KB
/
8.4-virtual-filesystem.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
import { resolve } from 'path'
// In-Memory Cache
class Cache {
constructor() {
this.cache = new Map();
}
async putEntry(key, value) {
return Promise.resolve(this.cache.set(key, value));
}
async getValue(key, options, callback) {
const val = await Promise.resolve(this.cache.get(key));
if (!val) {
const err = new Error(`ENOENT, open "${key}"`)
err.code = 'ENOENT'
err.errno = 34
err.path = key
throw err;
}
return val;
}
}
// FS Adapter
const createFSAdapter = cache => ({
readFile(filename, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
} else if (typeof options === 'string') {
options = { encoding: options }
}
cache.getValue(resolve(filename))
.then(val => callback(null, val))
.catch(callback);
},
writeFile(filename, contents, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
} else if (typeof options === 'string') {
options = { encoding: options }
}
cache.putEntry(resolve(filename), contents)
.then((res) => callback(null, res))
.catch(callback)
}
})
const cache = new Cache();
const fs = createFSAdapter(cache)
fs.writeFile('file.txt', 'Hello!', () => {
fs.readFile('file.txt', { encoding: 'utf8' }, (err, res) => {
if (err) {
return console.error(err)
}
console.log('Read result', res)
})
})
// try to read a missing file
fs.readFile('missing.txt', { encoding: 'utf8' }, (err, res) => {
console.error(err)
})