Deno - Copy FIle Examples

This tutorial shows you how to copy a file in Deno.

To duplicate a file, it can be done by reading a file and then writing the contents to another file located in a different path. However, Deno has the methods to simplify that process. Below are the examples of how to copy a file in Deno.

Copy File

In order to copy a file, you need to pass both --allow-read and --allow-write flags. That's because Deno needs to read the file first before writing the file in another location.

Using Deno.copyFile

Deno.copyFile is used to copy a file's contents and permission to another path asynchronously. If the target path already exists, it will overwrite the existing file. If used to copy a directory, it will throw NotFound error. If the target is a directory, it will throw an error as well.

  function Deno.copyFile(fromPath: string | URL, toPath: string | URL): Promise

There are two arguments you have to pass, the first one is the path to the source, while the second is the target path. Both paths can be absolute or relative. If you choose to use a relative path, it must be relative to the working directory. The default working directory is the directory where you run the deno run command. You can change it using Deno.chdir command.

Below is the usage example.

  await Deno.copyFile('hello.txt', 'hello_copy.txt');

Using Deno.copyFileSync

This function is similar to copyFile, but it copies a file synchronously.

  function Deno.copyFileSync(fromPath: string | URL, toPath: string | URL): void

Below is the usage example.

  Deno.copyFileSync('hello1.txt', 'hello_copy.txt');

Error Handling

An error can occur while trying to copy a file. For example, if the file to copy doesn't exist.

  error: Uncaught (in promise) NotFound: File not found
      at processResponse (core.js:223:11)
      at Object.jsonOpAsync (core.js:240:12)
      at async Object.copyFile (deno:cli/rt/30_fs.js:49:5)
      at async file:///home/ivan/Projects/deno/src/examples/file_copy.ts:1:1

Another common error is the lack of permission.

  Check file:///home/ivan/Projects/deno/src/examples/file_copy.ts
  error: Uncaught (in promise) PermissionDenied: Permission denied (os error 13)
      at processResponse (core.js:223:11)
      at Object.jsonOpAsync (core.js:240:12)
      at async Object.copyFile (deno:cli/rt/30_fs.js:49:5)
      at async file:///home/ivan/Projects/deno/src/examples/file_copy.ts:1:1

Handling the error is the same as handling other types of error. You only need to wrap the code inside a try-catch block.

  try {
    await Deno.copyFile('hello.txt', 'hello_copy.txt');
  } catch (err) {
    console.error(err);
  }

That's how to copy a file using Deno. You can choose to do it asynchronously or synchronously. The methods above cannot be used to copy a folder or multiple files. In case there are more than one files to copy, you need to perform iteration.

 

Related Posts: