2020-07-27 20:18:52 +02:00
|
|
|
const fss = require('fs');
|
|
|
|
const fs = fss.promises;
|
2018-02-06 23:31:18 +01:00
|
|
|
const path = require('path');
|
|
|
|
const mkdirp = require('mkdirp');
|
|
|
|
|
|
|
|
class FSStorage {
|
|
|
|
constructor(config, log) {
|
|
|
|
this.log = log;
|
|
|
|
this.dir = config.file_dir;
|
|
|
|
mkdirp.sync(this.dir);
|
|
|
|
}
|
|
|
|
|
|
|
|
async length(id) {
|
2020-07-27 20:18:52 +02:00
|
|
|
const result = await fs.stat(path.join(this.dir, id));
|
2018-02-06 23:31:18 +01:00
|
|
|
return result.size;
|
|
|
|
}
|
|
|
|
|
|
|
|
getStream(id) {
|
2020-07-27 20:18:52 +02:00
|
|
|
return fss.createReadStream(path.join(this.dir, id));
|
2018-02-06 23:31:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
set(id, file) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const filepath = path.join(this.dir, id);
|
2020-07-27 20:18:52 +02:00
|
|
|
const fstream = fss.createWriteStream(filepath);
|
2018-02-06 23:31:18 +01:00
|
|
|
file.pipe(fstream);
|
2018-05-31 23:06:25 +02:00
|
|
|
file.on('error', err => {
|
|
|
|
fstream.destroy(err);
|
2018-02-06 23:31:18 +01:00
|
|
|
});
|
|
|
|
fstream.on('error', err => {
|
2020-07-27 20:18:52 +02:00
|
|
|
this.del(id);
|
2018-02-06 23:31:18 +01:00
|
|
|
reject(err);
|
|
|
|
});
|
|
|
|
fstream.on('finish', resolve);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-07-27 20:18:52 +02:00
|
|
|
async del(id) {
|
|
|
|
try {
|
|
|
|
await fs.unlink(path.join(this.dir, id));
|
|
|
|
} catch (e) {
|
|
|
|
// ignore local fs issues
|
|
|
|
}
|
2018-02-06 23:31:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
ping() {
|
|
|
|
return Promise.resolve();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = FSStorage;
|