fsPromises.copyFile(src, dest[, mode])


  • src <string> | <Buffer> | <URL> 要复制的源文件名
  • dest <string> | <Buffer> | <URL> 复制操作的目标文件名
  • mode <integer> 可选修饰符,用于指定复制操作的行为。可以创建一个由两个或更多值按位 OR 组成的掩码(例如 fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE默认值: 0
    • fs.constants.COPYFILE_EXCL:如果 dest 已经存在,复制操作将失败。
    • fs.constants.COPYFILE_FICLONE:复制操作将尝试创建一个写时复制的 reflink。如果平台不支持写时复制,则使用备用的复制机制。
    • fs.constants.COPYFILE_FICLONE_FORCE:复制操作将尝试创建一个写时复制的 reflink。如果平台不支持写时复制,则操作将失败。
  • 返回:<Promise> 成功时返回 undefined

异步地将 src 复制到 dest。默认情况下,如果 dest 已经存在,会被覆盖。

【Asynchronously copies src to dest. By default, dest is overwritten if it already exists.】

无法保证复制操作的原子性。如果在目标文件已被打开以进行写入后发生错误,将尝试删除目标文件。

【No guarantees are made about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, an attempt will be made to remove the destination.】

import { copyFile, constants } from 'node:fs/promises';

try {
  await copyFile('source.txt', 'destination.txt');
  console.log('source.txt was copied to destination.txt');
} catch {
  console.error('The file could not be copied');
}

// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
try {
  await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
  console.log('source.txt was copied to destination.txt');
} catch {
  console.error('The file could not be copied');
}