fs.copyFile(src, dest[, mode], callback)
src<string> | <Buffer> | <URL> 要复制的源文件名dest<string> | <Buffer> | <URL> 复制操作的目标文件名mode<integer> 用于复制操作的修饰符。默认值:0。callback<Function>err<Error>
异步地将 src 复制到 dest。默认情况下,如果 dest 已存在,则会被覆盖。传递给回调函数的参数除了可能的异常之外,没有其他参数。Node.js 不保证复制操作的原子性。如果在目标文件被打开以进行写入后发生错误,Node.js 将尝试删除目标文件。
【Asynchronously copies src to dest. By default, dest is overwritten if it
already exists. No arguments other than a possible exception are given to the
callback function. 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.】
mode 是一个可选的整数,用于指定复制操作的行为。可以创建一个由两个或多个值按位 OR 组合而成的掩码(例如 fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE)。
fs.constants.COPYFILE_EXCL:如果dest已经存在,复制操作将失败。fs.constants.COPYFILE_FICLONE:复制操作将尝试创建一个写时复制的反向链接。如果平台不支持写时复制,则将使用备用复制机制。fs.constants.COPYFILE_FICLONE_FORCE:复制操作将尝试创建一个写时复制的反向链接。如果平台不支持写时复制,则操作将失败。
import { copyFile, constants } from 'node:fs';
function callback(err) {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
}
// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);