/
Gabryelf
/
Pixel-Orb
Обзор
Документация
Войти
/
Gabryelf
/
Pixel-Orb
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/server/storage/fileStorage.js
111 строк
3 KB
Valeev Serj
restruct_v0.0.1
07 авг 2026, 22:50
07 авг 2026, 22:50
41f78a4
Код
Авторство
О чём код?
const fs = require('fs'); const path = require('path'); class FileStorage { constructor() { this.uploadDir = path.join(__dirname, '../../../uploads'); if (!fs.existsSync(this.uploadDir)) { fs.mkdirSync(this.uploadDir, { recursive: true }); } } async saveFile(fileName, data, type = 'image') { const id = Date.now() + '_' + Math.random().toString(36).substr(2, 6); const ext = path.extname(fileName); const filename = id + ext; const filepath = path.join(this.uploadDir, filename); // Определяем подпапку по типу const typeDir = path.join(this.uploadDir, type); if (!fs.existsSync(typeDir)) { fs.mkdirSync(typeDir, { recursive: true }); } const fullPath = path.join(typeDir, filename); // Сохраняем файл if (Buffer.isBuffer(data)) { fs.writeFileSync(fullPath, data); } else if (data.pipe) { // Stream return new Promise((resolve, reject) => { const stream = fs.createWriteStream(fullPath); data.pipe(stream); stream.on('finish', () => { resolve({ id, filename, path: fullPath, url: `/uploads/${type}/${filename}` }); }); stream.on('error', reject); }); } return { id, filename, path: fullPath, url: `/uploads/${type}/${filename}` }; } async getFile(id, type = 'image') { const typeDir = path.join(this.uploadDir, type); if (!fs.existsSync(typeDir)) { return null; } const files = fs.readdirSync(typeDir); for (let file of files) { if (file.startsWith(id)) { const filepath = path.join(typeDir, file); const data = fs.readFileSync(filepath); return { id, filename: file, data, path: filepath, url: `/uploads/${type}/${file}` }; } } return null; } async deleteFile(id, type = 'image') { const typeDir = path.join(this.uploadDir, type); if (!fs.existsSync(typeDir)) { return false; } const files = fs.readdirSync(typeDir); for (let file of files) { if (file.startsWith(id)) { const filepath = path.join(typeDir, file); fs.unlinkSync(filepath); return true; } } return false; } listFiles(type = 'image') { const typeDir = path.join(this.uploadDir, type); if (!fs.existsSync(typeDir)) { return []; } const files = fs.readdirSync(typeDir); return files.map(file => ({ id: file.split('_')[0], filename: file, url: `/uploads/${type}/${file}`, size: fs.statSync(path.join(typeDir, file)).size })); } } module.exports = new FileStorage();