Node.js

Copy a file with explicit destination behavior

Use copyFile to duplicate a regular file. Add COPYFILE_EXCL when overwriting an existing destination would be a mistake rather than the intended behavior.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
  const source = join(directory, "source.txt");
  const target = join(directory, "copy.txt");
  await fs.writeFile(source, "copy me");
  await fs.copyFile(source, target, fs.constants.COPYFILE_EXCL);
  console.log(await fs.readFile(target, "utf8"));
} finally {
  await fs.rm(directory, {recursive: true, force: true});
}

How it works

The destination receives the source file’s bytes. The explicit exclusivity flag documents that this operation should create a new copy rather than replace one silently. Awaiting the promise ensures subsequent reads happen after the copy completes.

Limits and mistakes

Copying does not remove the source and is not a directory-tree copy. Do not assume it provides atomic replacement or a complete backup of every metadata attribute. Both source and destination can encounter permission or storage errors.

Check the result

Expect copy me. Run the copy a second time in a disposable fixture to confirm the chosen no-overwrite behavior is enforced.

Sources

Reference documentation for the behavior used in this guide: