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

Node.js实现文件复制移动重命名且不删除原文件方案求助

Node.js 实现文件复制并重命名(保留原文件)

因为fs.rename是移动文件系统条目,会直接移除原文件;要保留原文件,必须通过复制+重命名的方式实现——复制时直接指定目标路径的新文件名即可完成操作。

以下是几种适合不同场景的实现方案:

1. 异步Promise方案(推荐,非阻塞)

使用Node.js内置的fs.promises API,支持异步/await,不会阻塞主线程,适合大多数业务场景:

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

async function copyAndRenameFile(sourcePath, targetDir, newFileName) {
  // 递归创建目标目录(不存在则自动生成)
  await fs.mkdir(targetDir, { recursive: true });
  // 拼接目标文件的完整路径
  const targetPath = path.join(targetDir, newFileName);
  // 执行复制操作,原文件会被保留
  await fs.copyFile(sourcePath, targetPath);
  console.log(`文件已复制并重命名至:${targetPath}`);
}

// 使用示例
copyAndRenameFile(
  './source-dir/original-file.txt',
  './target-dir',
  'renamed-file.txt'
).catch(err => console.error('操作失败:', err));

2. 同步方案(适合简单脚本)

如果是小型脚本,可使用同步API,逻辑更直接,但会阻塞主线程:

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

function copyAndRenameFileSync(sourcePath, targetDir, newFileName) {
  // 确保目标目录存在
  if (!fs.existsSync(targetDir)) {
    fs.mkdirSync(targetDir, { recursive: true });
  }
  const targetPath = path.join(targetDir, newFileName);
  fs.copyFileSync(sourcePath, targetPath);
  console.log(`文件已复制并重命名至:${targetPath}`);
}

// 使用示例
try {
  copyAndRenameFileSync(
    './source-dir/original-file.txt',
    './target-dir',
    'renamed-file.txt'
  );
} catch (err) {
  console.error('操作失败:', err);
}

3. 大文件流式处理(避免内存溢出)

处理大文件(如视频、压缩包)时,推荐使用流式复制,避免一次性加载文件到内存:

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

function copyLargeFileAndRename(sourcePath, targetDir, newFileName) {
  const targetPath = path.join(targetDir, newFileName);
  
  // 创建目标目录
  fs.mkdirSync(targetDir, { recursive: true });
  
  // 创建读写流并建立管道
  const readStream = fs.createReadStream(sourcePath);
  const writeStream = fs.createWriteStream(targetPath);

  readStream.pipe(writeStream);

  // 监听流事件处理错误和完成状态
  readStream.on('error', err => console.error('读取文件失败:', err));
  writeStream.on('finish', () => console.log(`大文件已复制并重命名至:${targetPath}`));
  writeStream.on('error', err => console.error('写入文件失败:', err));
}

// 使用示例
copyLargeFileAndRename(
  './source-dir/large-video.mp4',
  './target-dir',
  'renamed-video.mp4'
);

补充说明

  • fs.copyFile默认会保留原文件的权限,若需要避免覆盖已存在的目标文件,可传入第三个参数fs.constants.COPYFILE_EXCL
  • 批量处理文件时,可通过fs.readdir遍历源目录,逐个调用上述函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 19:17:18