Im trying to copy one of my files from one directory into another directory
.then((answers) => {
//installing dependencies in specified directory
try{
console.log(answers.dependencies)
//answers.dependencies
let dest = "/Users/[name]/Code/test"
let copyingFile = fs.copyFile('/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js', "/Users/[name]/Code/test")
} catch(error) {
console.log("Error when copying file: ", error )
}
console.log("file coppied". copyingFile)
})
}
but whenever I try to run the program I get this error in javascript
[Error: EISDIR: illegal operation on a directory, copyfile '/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js' -> '/Users/[name]/Code/test'] {
errno: -21,
code: 'EISDIR',
syscall: 'copyfile',
path: '/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js',
dest: '/Users/[name]/Code/test'
}
If you are using the fs.copyFile then you need to specify the filename on the destination and use a callback to check for errors like so:
fs.copyFile(
'/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js',
'/Users/[name]/Code/test/testFile.js', (err) => {
if (err) {
console.error(err);
//Handle error
}
});
As mentioned in the comments, the second argument to the copyFile
function must be the destination file path (not the path to a directory).
If you plan to copy more than one file to a destination directory, you can abstract the file path manipulation using a function, for example:
copy_to_dir.mjs
:
import { copyFile } from "node:fs/promises";
import { basename, join } from "node:path";
export function copyToDir(srcFilePath, destDirPath, mode) {
const destFilePath = join(destDirPath, basename(srcFilePath));
return copyFile(srcFilePath, destFilePath, mode);
}
Then you can use the function with the same arguments in your original code:
import { copyToDir } from "./copy_to_dir.mjs";
await copyToDir(
"/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js",
"/Users/[name]/Code/test",
);
and the file will be copied to /Users/[name]/Code/test/testFile.js
.
The destination has to be a name for the actual file, not a directory.
it still doesnt work, how would I copy a file from one directory into another file? Doesn’t it have to copy one file into a directory
If “/Users/[name]/Code/test” is a directory, you have to change the path to “/Users/[name]/Code/test/testFile.js”
Basically
.copyFile()
does not work like thecp
command from the shell.