🎈 pref: 优化文件操作和日志记录

- 将 `fs.promises` 替换为 `fs` 以简化代码
- 在删除文件和目录后添加日志记录信息
- 优化 `deleteFolderRecursive` 函数中的文件处理逻辑
- 优化 `copyFiles` 函数中的文件拷贝逻辑
- 优化 `toBase64` 函数中的文件读取逻辑
This commit is contained in:
zhiyu1998 2024-09-11 11:02:13 +08:00
parent b467873397
commit 61bb052f68

View File

@ -1,4 +1,4 @@
import fs from "node:fs"; import { promises as fs } from "fs";
import path from "path"; import path from "path";
// 常量提取 // 常量提取
@ -14,7 +14,7 @@ const mimeTypes = {
// 通用错误处理函数 // 通用错误处理函数
function handleError(err) { function handleError(err) {
logger.error(err); logger.error(`错误: ${err.message}\n堆栈: ${err.stack}`);
throw err; throw err;
} }
@ -25,8 +25,9 @@ function handleError(err) {
*/ */
export async function checkAndRemoveFile(file) { export async function checkAndRemoveFile(file) {
try { try {
await fs.promises.access(file); await fs.access(file);
await fs.promises.unlink(file); await fs.unlink(file);
logger.info(`文件 ${file} 删除成功。`);
} catch (err) { } catch (err) {
if (err.code !== 'ENOENT') { if (err.code !== 'ENOENT') {
handleError(err); handleError(err);
@ -41,10 +42,11 @@ export async function checkAndRemoveFile(file) {
*/ */
export async function mkdirIfNotExists(dir) { export async function mkdirIfNotExists(dir) {
try { try {
await fs.promises.access(dir); await fs.access(dir);
} catch (err) { } catch (err) {
if (err.code === 'ENOENT') { if (err.code === 'ENOENT') {
await fs.promises.mkdir(dir, { recursive: true }); await fs.mkdir(dir, { recursive: true });
logger.info(`目录 ${dir} 创建成功。`);
} else { } else {
handleError(err); handleError(err);
} }
@ -61,18 +63,16 @@ export async function deleteFolderRecursive(folderPath) {
const files = await readCurrentDir(folderPath); const files = await readCurrentDir(folderPath);
const actions = files.map(async (file) => { const actions = files.map(async (file) => {
const curPath = path.join(folderPath, file); const curPath = path.join(folderPath, file);
const stat = await fs.lstat(curPath);
const stat = await fs.promises.lstat(curPath);
if (stat.isDirectory()) { if (stat.isDirectory()) {
// recurse
return deleteFolderRecursive(curPath); return deleteFolderRecursive(curPath);
} else { } else {
// delete file return fs.unlink(curPath);
return fs.promises.unlink(curPath);
} }
}); });
await Promise.allSettled(actions); await Promise.allSettled(actions);
logger.info(`文件夹 ${folderPath} 中的所有文件删除成功。`);
return files.length; return files.length;
} catch (error) { } catch (error) {
handleError(error); handleError(error);
@ -87,7 +87,7 @@ export async function deleteFolderRecursive(folderPath) {
*/ */
export async function readCurrentDir(dirPath) { export async function readCurrentDir(dirPath) {
try { try {
return await fs.promises.readdir(dirPath); return await fs.readdir(dirPath);
} catch (err) { } catch (err) {
handleError(err); handleError(err);
} }
@ -105,26 +105,24 @@ export async function copyFiles(srcDir, destDir, specificFiles = []) {
await mkdirIfNotExists(destDir); await mkdirIfNotExists(destDir);
const files = await readCurrentDir(srcDir); const files = await readCurrentDir(srcDir);
// 如果 specificFiles 数组为空,拷贝全部文件;否则只拷贝指定文件
const filesToCopy = specificFiles.length > 0 const filesToCopy = specificFiles.length > 0
? files.filter(file => specificFiles.includes(file)) ? files.filter(file => specificFiles.includes(file))
: files; : files;
logger.info(logger.yellow(`[R插件][拷贝文件] 正在将 ${srcDir} 的文件拷贝到 ${destDir}`)); logger.info(`[R插件][拷贝文件] 正在将 ${srcDir} 的文件拷贝到 ${destDir}`);
// 用于保存拷贝了哪些文件
const copiedFiles = []; const copiedFiles = [];
for (const file of filesToCopy) { for (const file of filesToCopy) {
const srcFile = path.join(srcDir, file); const srcFile = path.join(srcDir, file);
const destFile = path.join(destDir, file); const destFile = path.join(destDir, file);
await fs.promises.copyFile(srcFile, destFile); await fs.copyFile(srcFile, destFile);
copiedFiles.push(file); copiedFiles.push(file);
} }
logger.info(logger.yellow(`[R插件][拷贝文件] 拷贝完成`)); logger.info(`[R插件][拷贝文件] 拷贝完成`);
return copiedFiles return copiedFiles;
} catch (error) { } catch (error) {
handleError(error); handleError(error);
return []; return [];
@ -138,9 +136,8 @@ export async function copyFiles(srcDir, destDir, specificFiles = []) {
*/ */
export async function toBase64(filePath) { export async function toBase64(filePath) {
try { try {
const fileData = await fs.promises.readFile(filePath); const fileData = await fs.readFile(filePath);
const base64Data = fileData.toString('base64'); const base64Data = fileData.toString('base64');
// 返回Base64字符串
return `data:${getMimeType(filePath)};base64,${base64Data}`; return `data:${getMimeType(filePath)};base64,${base64Data}`;
} catch (error) { } catch (error) {
handleError(error); handleError(error);
@ -164,11 +161,10 @@ function getMimeType(filePath) {
*/ */
export async function getMediaFilesAndOthers(folderPath) { export async function getMediaFilesAndOthers(folderPath) {
try { try {
const files = await fs.promises.readdir(folderPath); const files = await fs.readdir(folderPath);
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']; const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
const videoExtensions = ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm']; const videoExtensions = ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm'];
// 初始化存储图片和视频的数组
const images = []; const images = [];
const videos = []; const videos = [];
const others = []; const others = [];