Cannot copy a Unix domain socket with fs.cp()
Production Risk
Low — only relevant when copying directories containing running service sockets.
Thrown when fs.cp() encounters a Unix domain socket file as the source. Socket files represent live IPC endpoints and cannot be meaningfully copied as their state is managed by the operating system, not stored as file content.
- 1Copying a directory tree that contains a Unix domain socket file
- 2Attempting to cp() a socket file path directly
Triggered when cp() encounters a file of type socket during traversal.
const fs = require('fs');
// If src-dir contains a .sock file:
fs.cpSync('./src-dir', './dest-dir', { recursive: true }); // throws on the socketexpected output
Error [ERR_FS_CP_SOCKET]: Cannot copy a socket file: '/src-dir/app.sock'
Fix
Filter out socket files during copy
WHEN When copying directories that may contain socket files
const fs = require('fs');
fs.cpSync('./src-dir', './dest-dir', {
recursive: true,
filter: (src) => {
const stat = fs.statSync(src);
return !stat.isSocket();
},
});Why this works
The filter callback excludes socket files from the copy operation.
const fs = require('fs');
// If src-dir contains a .sock file:
fs.cpSync('./src-dir', './dest-dir', { recursive: true }); // throws on the socket // this triggers ERR_FS_CP_SOCKETtry {
// operation that may throw ERR_FS_CP_SOCKET
riskyOperation()
} catch (err) {
if (err.code === 'ERR_FS_CP_SOCKET') {
console.error('ERR_FS_CP_SOCKET:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_fs_cp_socket(...args) {
// validate args here
return performOperation(...args)
}✕ Copy directories with socket files without a filter
Socket files cannot be duplicated; they represent live OS-managed IPC endpoints.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev