fs.copyFileSync(src, dest[, mode])


同步将 src 复制到 dest。默认情况下,如果 dest 已经存在,会被覆盖。返回 undefined。Node.js 不保证复制操作的原子性。如果在目标文件已打开用于写入后发生错误,Node.js 会尝试删除目标文件。

🌐 Synchronously copies src to dest. By default, dest is overwritten if it already exists. Returns undefined. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.

符号链接会被跟随。如果 src 是符号链接,则会复制目标文件。如果 dest 是符号链接,目标文件会被覆盖,除非 mode 包含 fs.constants.COPYFILE_EXCL。

🌐 Symbolic links are followed. If src is a symbolic link, the target file is copied. If dest is a symbolic link, the target file is overwritten unless mode contains fs.constants.COPYFILE_EXCL.

mode 是一个可选的整数,用于指定复制操作的行为。可以创建一个由两个或多个值按位 OR 组合而成的掩码(例如 fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE)。

  • fs.constants.COPYFILE_EXCL:如果 dest 已经存在,复制操作将失败。
  • fs.constants.COPYFILE_FICLONE:复制操作将尝试创建一个写时复制(reflink)。如果平台不支持写时复制,则会使用回退的复制机制。
  • fs.constants.COPYFILE_FICLONE_FORCE:复制操作将尝试创建一个写时复制的重链接。如果平台不支持写时复制,则操作将失败。
import { copyFileSync, constants } from 'node:fs';

// destination.txt will be created or overwritten by default.
copyFileSync('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');

// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);