discordjs-file-explorer
Version:
File explorer command for Discord.JS bots
90 lines (77 loc) • 2.68 kB
JavaScript
const fs = require('fs');
const path = require('path');
const fetch = require('node-fetch');
module.exports = class FileManagerDJS {
constructor(rootPath) {
this.root = rootPath;
this.currentPath = '/';
this.pathFiles = {
all: [],
folders: [],
files: [],
}
this.read();
}
read() {
this.pathFiles = {
all: [],
folders: [],
files: [],
};
const files = fs.readdirSync(path.join(__dirname, `${this.root}${this.currentPath}`), { withFileTypes: true });
files.forEach(file => {
if (file.isDirectory()) {
this.pathFiles.folders.push(file);
} else this.pathFiles.files.push(file);;
})
this.pathFiles.all = [...this.pathFiles.folders, ...this.pathFiles.files];
return this;
}
goBack() {
if (this.currentPath == '/') return this;
const newPath = this.currentPath.split('/');
newPath.splice(newPath.length - 2, 1);
this.currentPath = newPath.join('/');
this.read();
return this;
}
goTo(dirName) {
if (!this.pathFiles.folders.some((file) => file.name == dirName)) return;
this.currentPath = this.currentPath + `${dirName}/`;
this.read();
return this;
}
getAll() {
return this.pathFiles.all;
}
getFolders() {
return this.pathFiles.folders;
}
getFiles() {
return this.pathFiles.files;
}
filePath(fileName) {
if (!this.pathFiles.files.some((file) => file.name == fileName)) return;
return path.join(__dirname, `${this.root}${this.currentPath}${fileName}`);
}
isRoot() {
return this.currentPath == '/';
}
deleteFile(fileName) {
if (!this.pathFiles.files.some((file) => file.name == fileName)) return;
fs.unlinkSync(this.filePath(fileName));
}
async downloadFromUrl(url, fileName, overwrite) {
await new Promise(async (resolve, reject) => {
if (!overwrite && this.pathFiles.files.some(file => file.name == fileName)) {
reject('directory already has a file with name ' + fileName);
return;
}
const res = await fetch(url);
const fileStream = fs.createWriteStream(path.join(__dirname, `${this.root}${this.currentPath}${fileName}`));
res.body.pipe(fileStream);
res.body.on('error', reject);
fileStream.on('finish', resolve);
})
}
}