Skip to content
jshacks.dev
Node.js

fs.promises.copyFile() in Node.js Explained With Examples

Copy a file with fs.promises.copyFile in Node.js 24 and 26: overwrite rules, COPYFILE_EXCL, copy-on-write, what is preserved, errors and backup patterns.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the Node.js, JavaScript and Vite logos.

Copying a file seems like a job for readFile followed by writeFile, and for a small file that works. It is also the wrong tool: it pulls the whole file through your program's memory, it needs two operations that can fail separately, and it ignores everything the operating system knows about copying efficiently. copyFile hands the whole job to the operating system, which can copy without moving the data through JavaScript at all, and on file systems that support it, without even duplicating the data on disk until one copy changes. This post covers fs.promises.copyFile from node:fs/promises on Node.js 24 and 26: the basic call, what it overwrites, the flags that change that, what a copy keeps and loses, the errors and the patterns it is good for. It is the companion of the rename post, which moves instead of copying, and the single-file counterpart of the cp post, which copies trees. Samples use temporary folders, and the output of each is exact.

The basic call

copyFile(source, destination[, mode]) copies one file and resolves with undefined. The destination is a file path, and the folder that holds it must already exist.

basic.mjsJavaScript
import { mkdtemp, writeFile, readFile, readdir, copyFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const dir = await mkdtemp(join(tmpdir(), "copy-"));
await writeFile(join(dir, "original.txt"), "important data");

console.log(await copyFile(join(dir, "original.txt"), join(dir, "backup.txt")));

console.log((await readdir(dir)).sort().join(","));
console.log(await readFile(join(dir, "backup.txt"), "utf8"));
Text
undefined
backup.txt,original.txt
important data

Both files exist afterward with the same content. Unlike rename, the source stays. The call is asynchronous and runs on the thread pool, and it does not read the file into your process, so copying a file of several gigabytes does not raise your program's memory use.

Overwriting is the default

If the destination already exists, copyFile replaces it, with no error.

overwrite.mjsJavaScript
import { mkdtemp, writeFile, readFile, copyFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const dir = await mkdtemp(join(tmpdir(), "copy-"));
await writeFile(join(dir, "new.txt"), "new");
await writeFile(join(dir, "target.txt"), "old");

await copyFile(join(dir, "new.txt"), join(dir, "target.txt"));

console.log(await readFile(join(dir, "target.txt"), "utf8"));
Text
new

The old content is lost. Sometimes that is what you want, such as refreshing a cached copy, and sometimes it is a bug, such as backing up over yesterday's backup.

Refusing to overwrite with COPYFILE_EXCL

The third argument is a mode made from flags in fs.constants. The flag COPYFILE_EXCL makes the call fail if the destination exists.

excl.mjsJavaScript
import { mkdtemp, writeFile, readFile, copyFile, constants } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const dir = await mkdtemp(join(tmpdir(), "copy-"));
await writeFile(join(dir, "new.txt"), "new");
await writeFile(join(dir, "target.txt"), "old");

try {
  await copyFile(join(dir, "new.txt"), join(dir, "target.txt"), constants.COPYFILE_EXCL);
} catch (err) {
  console.log(err.code);
}

console.log(await readFile(join(dir, "target.txt"), "utf8"));
Text
EEXIST
old

The copy was refused and the existing file kept its content. The check and the copy happen together in the operating system, so there is no race between them, which makes this the dependable way to copy without clobbering. The same constants are available from node:fs as fs.constants, and node:fs/promises exports constants too.

The three flags are these, and you combine them with the bitwise OR operator, |.

  • COPYFILE_EXCL fails if the destination exists.

  • COPYFILE_FICLONE tries a copy-on-write clone, and falls back to a normal copy if the file system cannot do it.

  • COPYFILE_FICLONE_FORCE requires a clone and fails with an error if the file system does not support it.

Copy-on-write clones

On file systems such as Btrfs, XFS with reflink support and APFS, a clone creates a second name for the same data blocks, and the system duplicates blocks only when either file is modified. The copy is nearly instant and uses almost no extra space. With COPYFILE_FICLONE, Node.js asks for this and quietly does a normal copy where it is unavailable.

clone.mjsJavaScript
import { mkdtemp, writeFile, readFile, copyFile, constants } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const dir = await mkdtemp(join(tmpdir(), "copy-"));
await writeFile(join(dir, "big.bin"), "payload");

await copyFile(join(dir, "big.bin"), join(dir, "clone.bin"), constants.COPYFILE_FICLONE);

console.log(await readFile(join(dir, "clone.bin"), "utf8"));
Text
payload

The result looks the same whether a clone or a real copy happened, and that is the point of the flag: it is a free optimization. Use COPYFILE_FICLONE_FORCE only when you must know that no data was duplicated, and handle the error it raises on file systems without support. Do not claim a speed-up for your workload without measuring it, since the benefit depends on the file system and on file size.

What a copy keeps and what it loses

A copy gets the content and the permission bits of the source. It does not get the timestamps, which are set to the time of the copy, and it does not keep other metadata such as extended attributes or ownership, unless your user and the system arrange it.

metadata.mjsJavaScript
import { mkdtemp, writeFile, chmod, utimes, stat, copyFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const dir = await mkdtemp(join(tmpdir(), "copy-"));
const source = join(dir, "source.txt");
const target = join(dir, "target.txt");

await writeFile(source, "x");
await chmod(source, 0o600);
await utimes(source, 0, 86400);

await copyFile(source, target);

const info = await stat(target);

console.log((info.mode & 0o777).toString(8));
console.log(info.mtimeMs === 86400000);
Text
600
false

The permission bits 600 carried over, and the modification time did not, since it was set at copy time, so the comparison with the source's time is false. If you need the original timestamps, set them after copying with utimes, reading them from stat of the source, or use cp with preserveTimestamps: true, covered in the cp post.

Errors

The usual failures are a missing source and a missing destination folder, and both report ENOENT.

errors.mjsJavaScript
import { mkdtemp, writeFile, copyFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const dir = await mkdtemp(join(tmpdir(), "copy-"));
await writeFile(join(dir, "real.txt"), "x");

const attempts = [
  [join(dir, "missing.txt"), join(dir, "out.txt")],
  [join(dir, "real.txt"), join(dir, "no-such-folder", "out.txt")],
];

for (const [from, to] of attempts) {
  try {
    await copyFile(from, to);
  } catch (err) {
    console.log(err.code, err.syscall);
  }
}
Text
ENOENT copyfile
ENOENT copyfile

Both messages carry the same code, so check the paths in the error object to see which side was missing: the error has path for the source and dest for the destination. EACCES means permission was refused on either side. A destination that is an existing folder fails too, because copyFile needs a file path, so build the full target with path.join(folder, basename(source)). And copyFile is for single files, so passing a folder as the source fails. Use cp with recursive: true for folders.

Backup with a timestamped name

A frequent pattern is to keep a backup before changing a file, and to name it so that earlier backups survive.

backup.mjsJavaScript
import { mkdtemp, writeFile, readdir, copyFile, constants } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, parse } from "node:path";

const dir = await mkdtemp(join(tmpdir(), "copy-"));
const file = join(dir, "settings.json");
await writeFile(file, "{}");

async function backup(path, label) {
  const { dir: folder, name, ext } = parse(path);
  const target = join(folder, `${name}.${label}${ext}`);
  await copyFile(path, target, constants.COPYFILE_EXCL);
  return target;
}

await backup(file, "before-upgrade");

try {
  await backup(file, "before-upgrade");
} catch (err) {
  console.log(err.code);
}

console.log((await readdir(dir)).sort().join("\n"));
Text
EEXIST
settings.before-upgrade.json
settings.json

The label here is fixed, so the second attempt is refused and the first backup survives. In real code the label would be a timestamp such as new Date().toISOString().replaceAll(":", "-"), since colons are not allowed in Windows file names. Using COPYFILE_EXCL means a backup is never overwritten by accident.

Copy then verify

For files that matter, confirm the copy before you remove or change the original. Comparing sizes catches truncation, and comparing a hash catches corruption, using the streaming hash from the crypto post.

verify.mjsJavaScript
import { mkdtemp, writeFile, copyFile, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const dir = await mkdtemp(join(tmpdir(), "copy-"));
await writeFile(join(dir, "a.bin"), "twelve bytes");

await copyFile(join(dir, "a.bin"), join(dir, "b.bin"));

const [a, b] = await Promise.all([stat(join(dir, "a.bin")), stat(join(dir, "b.bin"))]);

console.log(a.size === b.size, a.size);
Text
true 12

A size check is cheap and catches the most common failures. A hash comparison reads both files fully, so reserve it for critical data.

When not to use copyFile

Use rename when you want to move a file and can stay on one file system, because it copies nothing. Use cp for folders, for filtering and for preserving timestamps. Use streams when you need to transform data on the way, such as compressing during a copy, with pipeline and createGzip as in the zlib post. Use readFile and writeFile only when the data passes through your code anyway.

Also inAsync
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.