-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (67 loc) · 1.92 KB
/
index.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
'use strict';
const path = require('path');
const fs = require('mz/fs');
const mkdirp = require('mz-modules/mkdirp');
class LocalDiskClient {
constructor(options) {
if (!options || !options.dir) {
throw new Error('need present options.dir');
}
this.dir = options.dir;
}
async upload(filepath, options) {
const destpath = this._getpath(options.key);
await this._ensureDirExists(destpath);
const content = await fs.readFile(filepath);
await fs.writeFile(destpath, content);
return { key: options.key };
}
async uploadBuffer(content, options) {
const filepath = this._getpath(options.key);
await this._ensureDirExists(filepath);
await fs.writeFile(filepath, content);
return { key: options.key };
}
async appendBuffer(content, options) {
const filepath = this._getpath(options.key);
await this._ensureDirExists(filepath);
await fs.appendFile(filepath, content);
return { key: options.key };
}
// stream or undefined
async createDownloadStream(key) {
const filepath = this._getpath(key);
if (await fs.exists(filepath)) {
return fs.createReadStream(filepath);
}
}
// bytes or undefined
async readBytes(key) {
const filepath = this._getpath(key);
if (await fs.exists(filepath)) {
return await fs.readFile(filepath);
}
}
async download(key, savePath) {
const filepath = this._getpath(key);
const content = await fs.readFile(filepath);
await fs.writeFile(savePath, content);
}
async remove(key) {
const filepath = this._getpath(key);
if (await fs.exists(filepath)) {
await fs.unlink(filepath);
}
}
async _ensureDirExists(filepath) {
return await mkdirp(path.dirname(filepath));
}
async list(prefix) {
const destpath = this._getpath(prefix);
return await fs.readdir(destpath);
}
_getpath(key) {
return path.join(this.dir, key);
}
}
module.exports = LocalDiskClient;