Copy Files and Directories in Node.js Safely. This independently written guide explains what to check, how to approach the task safely and where common assumptions can fail.
Two APIs for different jobs
Node.js provides fs.copyFile for copying a single file and fs.cp for copying files or directory trees. Both have promise-based forms under node:fs/promises. Prefer these built-in APIs when they cover your use case, rather than adding a dependency solely to copy directories.
Copy a single file with promises
For one file, use an asynchronous operation and handle errors explicitly:
import { copyFile } from "node:fs/promises";
try {
await copyFile("./input.txt", "./backup/input.txt");
console.log("Copied successfully");
} catch (error) {
console.error("Copy failed:", error.message);
}
The destination directory must exist, and the default operation may overwrite a destination file.
Avoid accidental overwrites
If preserving an existing destination matters, pass the COPYFILE_EXCL flag from node:fs to copyFile. Treat an EEXIST error as an expected case, not an unexplained failure. Consider temporary files and an atomic rename when consumers must never observe a partially written output.
Copy a directory recursively
On supported Node.js versions, fs.cp can copy a directory tree:
import { cp } from "node:fs/promises";
await cp("./site", "./site-backup", { recursive: true });
Choose overwrite, errorOnExist and filter options deliberately. Always confirm that the chosen source and destination are what you intended before copying large trees.
Validate paths from users
If a web request supplies file names, do not concatenate them directly into a privileged filesystem path. Resolve them against an allowed root directory and reject attempts to escape that root. Remember that symlinks, permissions and race conditions can complicate naive path checks. A file-copy helper is not a substitute for an authorization policy.
Handle permissions and special files
Expect different behavior across Linux, Windows and network-mounted filesystems. Not every metadata attribute or permission is preserved exactly. Log failures with enough context for diagnosis, but avoid logging credentials or personal file contents.
Test the copy result
Use temporary test directories to cover missing files, existing targets, nested folders and permission errors. If data integrity is critical, compare file sizes or hashes after the operation. Built-in copy operations help with convenience but do not replace a versioned backup system.
Key takeaways
Confirm version-specific details in the official documentation before changing a live environment. Work from a backup, record configuration decisions and test the result under realistic conditions.
Source for further reading: original topic reference. This article is independently written and does not reproduce the source text.






