ERR_FS_CP_NON_DIR_TO_DIR
Node.jsERRORNotableFilesystemHIGH confidence

Cannot copy a non-directory source to a directory destination

Production Risk

Low — check argument order and destination type in copy scripts.

What this means

Thrown when fs.cp() is asked to copy a non-directory source (e.g. a regular file) to a destination that already exists as a directory. You cannot overwrite a directory with a file.

Why it happens
  1. 1Source is a file and destination is an existing directory
  2. 2Accidentally swapping source and destination arguments
How to reproduce

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

trigger — this will error
trigger — this will error
const fs = require('fs');
// 'dest-dir' already exists as a directory
fs.cpSync('./file.txt', './dest-dir'); // throws

expected output

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

Fix

Copy the file to a path inside the destination directory

WHEN When you want to place a file inside a directory

Copy the file to a path inside the destination directory
const path = require('path');
const fs = require('fs');
const destFile = path.join('./dest-dir', 'file.txt');
fs.cpSync('./file.txt', destFile);

Why this works

Specifying a full destination file path (not a directory) places the file correctly.

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

Use a directory path as the destination when copying a single file

cp() does not auto-place a file inside a directory; it treats the destination as the full target path.

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