socio
Version:
A WebSocket Real-Time Communication (RTC) API framework.
48 lines (47 loc) • 2.2 kB
JavaScript
import fs from 'fs';
import { default as os_path } from "path";
import pako from 'pako';
export function SaveFilesToDiskPath(string_array_path, files) {
return new Promise((res, rej) => {
try {
if (!string_array_path || !files)
return rej({ result: 0, error: 'SaveFilesToDiskPath: Function arguments are falsy. [#SaveFilesToDiskPath-falsy-args]' });
const entries = files instanceof Map ? files.entries() : Object.entries(files);
for (const [filename, file_data] of entries) {
const file_path = os_path.join(...string_array_path, filename);
const bin = pako.inflate(file_data.bin);
fs.writeFileSync(file_path, bin, { flag: 'w' });
}
res({ result: 1 });
}
catch (e) {
rej({ result: 0, error: e });
}
});
}
export function ReadFilesFromDisk(file_paths) {
return new Promise((res, rej) => {
try {
if (typeof file_paths !== 'object')
return rej({ result: 0, error: 'ReadFilesFromDisk: file_paths argument must be an array of string paths. [#file-paths-must-be-array]' });
if (!file_paths?.length)
return rej({ result: 0, error: 'ReadFilesFromDisk: No file_paths provided. [#no-file-paths]' });
if (file_paths.some(fp => typeof fp !== 'string'))
return rej({ result: 0, error: 'ReadFilesFromDisk: file_paths argument must be an array of string paths. [#file-paths-must-be-array-of-string]' });
const files = new Map();
for (const path of file_paths) {
const filename = os_path.basename(path);
const file = fs.readFileSync(path);
files.set(filename, { meta: { size: file.byteLength }, bin: pako.deflate(file.buffer) });
}
res({ result: 1, files });
}
catch (e) {
rej({ result: 0, error: e?.message || String(e) });
}
});
}
export function MapPathsToFolder(folder_path, relative_file_paths) {
const fp = os_path.join(...folder_path);
return relative_file_paths.map(p => os_path.join(fp, p));
}