fox-send/server/storage/fs.js

52 lines
1.0 KiB
JavaScript
Raw Normal View History

2020-07-27 18:18:52 +00:00
const fss = require('fs');
const fs = fss.promises;
2018-02-06 22:31:18 +00: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 18:18:52 +00:00
const result = await fs.stat(path.join(this.dir, id));
2018-02-06 22:31:18 +00:00
return result.size;
}
getStream(id) {
2020-07-27 18:18:52 +00:00
return fss.createReadStream(path.join(this.dir, id));
2018-02-06 22:31:18 +00:00
}
set(id, file) {
return new Promise((resolve, reject) => {
const filepath = path.join(this.dir, id);
2020-07-27 18:18:52 +00:00
const fstream = fss.createWriteStream(filepath);
2018-02-06 22:31:18 +00:00
file.pipe(fstream);
file.on('error', err => {
fstream.destroy(err);
2018-02-06 22:31:18 +00:00
});
fstream.on('error', err => {
2020-07-27 18:18:52 +00:00
this.del(id);
2018-02-06 22:31:18 +00:00
reject(err);
});
fstream.on('finish', resolve);
});
}
2020-07-27 18:18:52 +00:00
async del(id) {
try {
await fs.unlink(path.join(this.dir, id));
} catch (e) {
// ignore local fs issues
}
2018-02-06 22:31:18 +00:00
}
ping() {
return Promise.resolve();
}
}
module.exports = FSStorage;