You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js实现文件夹合并:追加后不超50MB才执行

实现按大小分组复制文件夹的解决方案

核心思路

通过计算每个源文件夹的大小,维护当前目标文件夹的已用空间,判断是否能将当前源文件夹加入当前组;若超出50MB限制,则新建目标文件夹存放,全程保证单个文件夹不被拆分。

具体实现步骤及代码

1. 实现异步计算文件夹大小的函数

const fs = require('fs').promises;
const path = require('path');

// 计算单个文件夹的总大小(字节)
async function calculateFolderSize(folderPath) {
  let totalSize = 0;
  const files = await fs.readdir(folderPath, { withFileTypes: true });

  for (const file of files) {
    const fullPath = path.join(folderPath, file.name);
    if (file.isDirectory()) {
      totalSize += await calculateFolderSize(fullPath);
    } else {
      const stats = await fs.stat(fullPath);
      totalSize += stats.size;
    }
  }
  return totalSize;
}

2. 初始化分组状态并遍历复制

// 配置参数
const MAX_TOTAL_SIZE = 50 * 1024 * 1024; // 50MB 转换为字节
const baseTargetDir = './target'; // 基础目标文件夹路径

// 维护当前分组状态
let currentTargetDir = path.join(baseTargetDir, 'group_1');
let currentUsedSize = 0;
let groupIndex = 1;

// 确保初始目标文件夹存在
await fs.mkdir(currentTargetDir, { recursive: true });

// 遍历源文件夹数组(你的temp_paths)
for await (const real_path of temp_paths) {
  // 获取当前源文件夹的大小
  const folderSize = await calculateFolderSize(real_path);

  // 判断是否能加入当前目标组
  if (currentUsedSize + folderSize <= MAX_TOTAL_SIZE) {
    // 复制到当前目标文件夹
    const destPath = path.join(currentTargetDir, path.basename(real_path));
    await fs.cp(real_path, destPath, { recursive: true, preserveTimestamps: true });
    currentUsedSize += folderSize;
  } else {
    // 新建目标文件夹
    groupIndex++;
    currentTargetDir = path.join(baseTargetDir, `group_${groupIndex}`);
    await fs.mkdir(currentTargetDir, { recursive: true });

    // 复制到新目标文件夹
    const destPath = path.join(currentTargetDir, path.basename(real_path));
    await fs.cp(real_path, destPath, { recursive: true, preserveTimestamps: true });
    currentUsedSize = folderSize;
  }
}

关键细节说明

  • 单位转换:50MB需转换为字节(50*1024*1024),避免大小判断出错。
  • 文件夹复制:使用fs.cp的recursive: true参数,完整复制文件夹结构,确保不拆分内部文件。
  • 目标文件夹命名:通过递增的groupIndex生成新文件夹(如group_1、group_2),保证分组清晰。
  • 错误处理:可根据需求在代码中添加try/catch块,处理文件夹读取、复制时的异常(比如权限问题)。

内容的提问来源于stack exchange,提问作者OnionRequestIntercepter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 11:32:37