skip to Main Content

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'
}

2

Answers


  1. 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
      }
    });
    
    Login or Signup to reply.
  2. 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);
    }
    

    Ref: fsPromises.copyFile, path.basename, path.join

    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.


    TypeScript code in playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search