Cannot copy a directory to a non-directory destination
Production Risk
Low — check destination type before copying in automation scripts.
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.
- 1Source is a directory and destination is an existing file
- 2Destination path was previously used for a file and now a directory is being copied there
Triggered by fs.cp() when it detects a type conflict between source (directory) and destination (file).
const fs = require('fs');
// 'dest.txt' exists as a file
fs.cpSync('./src-dir', './dest.txt', { recursive: true }); // throwsexpected 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
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
fs.cpSync('./src-dir', './dest-dir-v2', { recursive: true });Why this works
Using a new path avoids the type conflict entirely.
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_DIRtry {
// 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
}
}// Validate inputs before calling the operation
function safe_err_fs_cp_dir_to_non_dir(...args) {
// validate args here
return performOperation(...args)
}✕ 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.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev