Created MediaLinksFile.

This commit is contained in:
moonstar-x 2021-06-12 02:13:54 -05:00
parent cfdfdd0418
commit 11aa6ba14f

View File

@ -0,0 +1,74 @@
const fs = require('fs');
const path = require('path');
const { FatalError } = require('../../errors');
class MediaLinksFile {
constructor(filename) {
this.file = path.join(process.cwd(), filename);
if (!fs.existsSync(this.file)) {
throw new FatalError('The specified file could not be found!');
}
}
read() {
return new Promise((resolve, reject) => {
fs.readFile(this.file, (err, data) => {
if (err) {
return reject(err);
}
return resolve(MediaLinksFile.parseBuffer(data));
});
});
}
write(newContent) {
return new Promise((resolve, reject) => {
fs.writeFile(this.file, newContent, null, (err) => {
if (err) {
return reject(err);
}
return resolve();
});
});
}
async removeFirstLink() {
const items = await this.read();
const serialized = MediaLinksFile.serialize(items.slice(1));
await this.write(serialized);
}
remove() {
return new Promise((resolve, reject) => {
fs.unlink(this.file, (err) => {
if (err) {
return reject(err);
}
return resolve();
});
});
}
static serialize(content) {
return content.map((line) => `${line}\r`).join('\n');
}
static parseBuffer(buffer) {
return buffer.toString()
.split('\n')
.filter((line) => line)
.map((line) => {
const returnCarriageIndex = line.indexOf('\r');
if (returnCarriageIndex < 0) {
return line;
}
return line.substring(0, returnCarriageIndex);
});
}
}
module.exports = MediaLinksFile;