Cannot copy a non-directory source to a directory destination
Production Risk
Low — check argument order and destination type in copy scripts.
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.
- 1Source is a file and destination is an existing directory
- 2Accidentally swapping source and destination arguments
Triggered by fs.cp() when it detects a type conflict (file source, directory destination).
const fs = require('fs');
// 'dest-dir' already exists as a directory
fs.cpSync('./file.txt', './dest-dir'); // throwsexpected 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
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.
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_DIRtry {
// 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
}
}// Validate inputs before calling the operation
function safe_err_fs_cp_non_dir_to_dir(...args) {
// validate args here
return performOperation(...args)
}✕ 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.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev