@opengis/fastify-table
Version:
core-plugins
87 lines (86 loc) • 3.2 kB
JavaScript
import fs from "node:fs";
import fsp from "node:fs/promises";
import path from "node:path";
import isFileExists from "../utils/isFileExists.js";
import isBuffer from "./utils/typeguards/isBuffer.js";
import isReadableStream from "./utils/typeguards/isReadableStream.js";
import getValidData from "./utils/getValidData.js";
import dataTypes from "./utils/handlers/dataTypes.js";
import getPath from "../utils/getPath.js";
const deleteFile = () => async (fp) => {
const filepath = getPath(fp);
if (!filepath || !(await isFileExists(filepath))) {
throw new Error("Файл не знайдено");
}
await fsp.rm(filepath);
};
const moveFile = () => async (fp, destFilepath) => {
const filepath = getPath(fp);
if (!filepath || !(await isFileExists(filepath))) {
throw new Error("Файл не знайдено");
}
await fsp.mkdir(path.dirname(filepath), { recursive: true });
await fsp.mkdir(path.dirname(destFilepath), { recursive: true });
await fsp.copyFile(filepath, destFilepath, fs.constants.COPYFILE_FICLONE);
await fsp.rm(filepath);
};
const downloadFile = () => async (fp, options = {}) => {
const filepath = getPath(fp, options);
if (options.debug) {
return { original: fp, full: filepath };
}
if (!filepath || !(await isFileExists(filepath))) {
return null;
}
if (options.buffer) {
return fsp.readFile(filepath);
}
const fileStream = fs.createReadStream(filepath);
return fileStream;
};
const fileExists = () => async (filepath, opt = {}) => isFileExists(getPath(filepath, opt));
const uploadFile = () => async (fp, data, opt = {}) => {
const filepath = getPath(fp, opt);
const validData = await getValidData({
data,
types: [dataTypes.buffer, dataTypes.path, dataTypes.stream],
});
// const validData = data;
if (!filepath) {
throw new Error("empty filepath");
}
await fsp.mkdir(path.dirname(filepath), { recursive: true });
try {
const exists = await isFileExists(filepath);
if (!exists) {
await fsp.writeFile(filepath, validData, opt);
}
else if (isBuffer(validData) || isReadableStream(validData)) {
await fsp.appendFile(filepath, validData, opt);
}
else {
await fsp.copyFile(validData, filepath);
}
return filepath;
}
catch (err) {
throw new Error(`Can't upload a file ${err.toString()}`);
}
};
const stat = () => async (filepath) => fsp.stat(getPath(filepath) || "");
const getFileSize = () => async (filepath) => (await fsp.stat(getPath(filepath) || "")).size;
const getMDate = () => async (filepath) => new Date((await fsp.stat(getPath(filepath) || "")).mtime);
const readdir = () => async (filepath) => fsp.readdir(getPath(filepath) || "");
export default function fsStorage() {
return {
deleteFile: deleteFile(),
downloadFile: downloadFile(),
uploadFile: uploadFile(),
fileExists: fileExists(),
stat: stat(),
moveFile: moveFile(),
getFileSize: getFileSize(),
getMDate: getMDate(),
readdir: readdir(),
};
}