newmax-utils
Version:
Utils & Libs for Newmax Tech
103 lines (102 loc) • 3.63 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileActions = void 0;
const zlib_1 = __importDefault(require("zlib"));
const archiver_1 = __importDefault(require("archiver"));
const path_1 = require("path");
const promises_1 = require("fs/promises");
const fs_1 = require("fs");
async function save(path, fileName, data) {
if (!(0, fs_1.existsSync)(path))
await (0, promises_1.mkdir)(path, { recursive: true });
const filePath = (0, path_1.join)(path, fileName);
await (0, promises_1.writeFile)(filePath, JSON.stringify(data));
return { path, fileName, filePath };
}
async function copy(path, fileName, moveFolder) {
if (!(0, fs_1.existsSync)(moveFolder))
await (0, promises_1.mkdir)(moveFolder, { recursive: true });
const source = (0, fs_1.createReadStream)((0, path_1.join)(path, fileName));
const dest = (0, fs_1.createWriteStream)((0, path_1.join)(moveFolder, fileName));
source.pipe(dest);
return { path, fileName, filePath: String(source.path) };
}
async function readFileAsync(filePath) {
try {
return await (0, promises_1.readFile)(filePath);
}
catch (err) {
console.error(`Error reading file: ${filePath}`, err);
throw err;
}
}
async function getDirFiles(dirPath) {
try {
return await (0, promises_1.readdir)(dirPath);
}
catch (err) {
console.error(`Error reading folder: ${dirPath}`);
throw err;
}
}
async function unzip(buffer) {
return new Promise((resolve, reject) => {
zlib_1.default.gunzip(buffer, (err, unzipped_buffer) => {
if (err) {
reject(err);
}
resolve(unzipped_buffer);
});
});
}
async function zipDirectory(sourceDir, outPath) {
return new Promise(async (resolve, reject) => {
const output = (0, fs_1.createWriteStream)(outPath);
const archive = (0, archiver_1.default)('zip', { zlib: { level: 9 } });
output.on('close', () => resolve());
archive.on('error', (err) => reject(err));
// Начинаем архивирование
archive.pipe(output);
try {
// Читаем содержимое директории
const files = await (0, promises_1.readdir)(sourceDir);
// Добавляем файлы из директории в архив
files.forEach((file) => {
const filePath = (0, path_1.join)(sourceDir, file);
archive.file(filePath, { name: file });
});
// Завершаем архивирование
await archive.finalize();
}
catch (err) {
reject(err);
}
});
}
async function getBase64Image(filePath) {
const image = await readFileAsync(filePath);
return `data:image/png;base64,${image.toString('base64')}`;
}
async function saveBase64Image(base64String, filePath) {
try {
const base64Data = base64String.replace(/^data:image\/png;base64,/, '');
await (0, promises_1.writeFile)(filePath, base64Data, 'base64');
console.log('Файл успешно сохранён:', filePath);
}
catch (err) {
console.error('Ошибка при сохранении файла:', err);
}
}
exports.fileActions = {
save,
copy,
readFileAsync,
getDirFiles,
unzip,
zipDirectory,
getBase64Image,
saveBase64Image,
};