ERR_FS_CP_DIR_TO_NON_DIR
Node.jsERRORNotableFilesystemHIGH confidence

Cannot copy a directory to a non-directory destination

Production Risk

Low — check destination type before copying in automation scripts.

What this means

Thrown when fs.cp() or fs.cpSync() is asked to copy a source directory but the destination already exists as a non-directory file. You cannot overwrite a file with a directory.

Why it happens
  1. 1Source is a directory and destination is an existing file
  2. 2Destination path was previously used for a file and now a directory is being copied there
How to reproduce

Triggered by fs.cp() when it detects a type conflict between source (directory) and destination (file).

trigger — this will error
trigger — this will error
const fs = require('fs');
// 'dest.txt' exists as a file
fs.cpSync('./src-dir', './dest.txt', { recursive: true }); // throws

expected output

Error [ERR_FS_CP_DIR_TO_NON_DIR]: Cannot overwrite non-directory './dest.txt' with directory './src-dir'

Fix 1

Remove or rename the destination file before copying

WHEN When the destination path must become a directory

Remove or rename the destination file before copying
const fs = require('fs');
fs.rmSync('./dest', { force: true });
fs.cpSync('./src-dir', './dest', { recursive: true });

Why this works

Removing the conflicting file clears the path for the directory copy.

Fix 2

Copy to a new destination path

WHEN When you do not want to remove the existing file

Copy to a new destination path
fs.cpSync('./src-dir', './dest-dir-v2', { recursive: true });

Why this works

Using a new path avoids the type conflict entirely.

Code examples
Triggerjs
const fs = require('fs');
// 'dest.txt' exists as a file
fs.cpSync('./src-dir', './dest.txt', { recursive: true }); // throws  // this triggers ERR_FS_CP_DIR_TO_NON_DIR
Handle in try/catchjs
try {
  // operation that may throw ERR_FS_CP_DIR_TO_NON_DIR
  riskyOperation()
} catch (err) {
  if (err.code === 'ERR_FS_CP_DIR_TO_NON_DIR') {
    console.error('ERR_FS_CP_DIR_TO_NON_DIR:', err.message)
  } else {
    throw err
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_fs_cp_dir_to_non_dir(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Assume fs.cp() will overwrite a file with a directory

A file and directory at the same path are fundamentally different types; Node.js rejects the overwrite.

Sources
Official documentation ↗

Node.js Error Codes Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Node.js errors