@opengis/fastify-table
Version:
core-plugins
101 lines (82 loc) • 3.13 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 (!await isFileExists(filepath)) {
throw new Error('Файл не знайдено');
}
await fsp.rm(filepath);
};
const moveFile = () => async (fp, destFilepath) => {
const filepath = getPath(fp);
if (!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.deleteFile(filepath);
};
const downloadFile = () => async (fp, options = {}) => {
const filepath = getPath(fp, options);
if (options.debug) {
return { original: fp, full: filepath };
}
if (!await isFileExists(filepath, options)) {
return null;
}
if (options.buffer) {
// const test = await readFile(filepath);
return fsp.readFile(filepath);
}
const fileStream = fs.createReadStream(filepath);
return fileStream;
};
const fileExists = () => async (filepath, opt = {}) => isFileExists(getPath(filepath, opt), 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;
await fsp.mkdir(path.dirname(filepath), { recursive: true });
try {
const exists = await isFileExists(validData);
if (!exists) {
await fsp.writeFile(filepath, validData, opt);
}
else if (isBuffer(validData) || isReadableStream(validData)) {
await fsp.writeFile(filepath, validData, opt);
}
else {
await fsp.copyFile(validData, filepath);
}
return filepath;
}
catch (err) {
// console.log(err.toString());
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(getPath(filepath)));
export default function fsStorage(opt) {
return {
deleteFile: deleteFile(opt),
downloadFile: downloadFile(opt),
uploadFile: uploadFile(opt),
fileExists: fileExists(opt),
stat: stat(opt),
moveFile: moveFile(opt),
getFileSize: getFileSize(opt),
getMDate: getMDate(opt),
readdir: readdir(opt),
};
}