Deno - Read and Write Files Examples

This tutorial shows you how to write and read files in Deno as text or bytes, either asynchronously or synchronously.

Deno provides some built-in functions that allows us to easily write data to files or read data from files. Below are the functions along with the examples.

Write Files

Deno has some functions to write data to a file. You can either write the data as a string or bytes, asynchronously or synchronously. For all functions, passing --allow-write flag is required.

Using Deno.writeTextFile

This function is used to write string data to a file. It overwrites the existing file if it already exists or creates a new file otherwise.

  function Deno.writeTextFile(path: string | URL, data: string, options?: WriteFileOptions): Promise<void>

Below is the usage example.

  await Deno.writeTextFile('hello.txt', 'Hello from www.woolha.com');

Using Deno.writeTextFileSync

This function is similar to writeTextFile, but it writes to a file synchronously.

  function Deno.writeTextFileSync(path: string | URL, data: string, options?: WriteFileOptions): void

Below is the usage example.

  Deno.writeTextFileSync('hello.txt', 'Hello from www.woolha.com');

Using Deno.writeFile

If you need more advanced options to write data to a file, you can use writeFile instead. It's used to write data to a file asynchronously. With the function, you can pass an options object as the third parameter.

  function Deno.writeFile(path: string | URL, data: Uint8Array, options?: WriteFileOptions): Promise<void>

WriteFileOptions has the following fields.

  • boolean append: If set to true, it will append the contents to the end of the file. Defaults to false.
  • boolean create: Whether to create the file if it doesn't already exist. Defaults to true.
  • number mode: Permissions applied to the file.

From the method signature, you are required to pass the data as Uint8Array. To convert a text into a Uint8Array, you can use TextEncoder.encode().

If you don't pass any option, it will use the default values. The below example creates a new file if the specified file doesn't exist or overwrites the contents if the file already exists.

  const encoder = new TextEncoder();
  const data = encoder.encode('Hello from www.woolha.com\n');
  await Deno.writeFile('hello.txt', data); // Create a new file or overwrite if already exists.

The next example passes the append option with the value is set to true. If the specified file exists, it will append the contents at the end of the file instead of overwrite the entire file. If the specified file doesn't exist, it will create a new one.

  await Deno.writeFile('hello.txt', data, { append: true }); // Add data to the end of the file.

The below example passes the create option with the value is set to false. It only works if the file already exists. Because the append option is not passed, it will overwrite the contents of the existing file. If the create option is set to false, you are also required to pass --allow-read option as Deno has to check the existence of the file first.

  await Deno.writeFile('hello.txt', data, { create: false }); // Only works if the file already exists.

If you need to set the permission of the file, you can pass mode option where the value is the permission number to be set.

  await Deno.writeFile('hello.txt', data, { mode: 0o777 }); // Set permissions to the file.

Using Deno.writeFileSync

This function is similar to writeFile, but it writes to a file synchronously.

  function Deno.writeFileSync(path: string | URL, data: Uint8Array, options?: WriteFileOptions): void

The parameters and the options are the same too, but it returns void instead of Promise.

  const encoder = new TextEncoder();
  const data = encoder.encode('Hello from www.woolha.com\n');
  Deno.writeFileSync('hello.txt', data); // Create a new file or overwrite if already exists.
  Deno.writeFileSync('hello.txt', data, { append: true }); // Add data to the end of the file.
  Deno.writeFileSync('hello.txt', data, { create: false }); // Only works if the file already exists.
  Deno.writeFileSync('hello.txt', data, { mode: 0o777 }); // Set permissions to the file.

Error Handling

Sometimes there can be an error while trying to write data to a file. For example, the user used to run the application doesn't have the permission to write to the file or directory.

  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 open (deno:cli/rt/30_files.js:44:17)
      at async Object.writeFile (deno:cli/rt/40_write_file.js:54:18)
      at async file:///home/ivan/Projects/deno/src/examples/file_write.ts:10:1

Handling the error is the same like handling other type of error. Just wrap the code inside a try-catch block.

  try {
    await Deno.writeTextFile('hello.txt', 'Hello from www.woolha.com');
  } catch (err) {
    console.error(err);
  }

 

Read Files

Deno has some functions to read the data of a file. You can read the data as byte or if the file contains text data, there are functions that read the contents as a string. You can choose to read a file asynchronously or synchronously. For all functions, passing --allow-read flag is required.

Using Deno.readTextFile

This function is used to read a file as utf8 encoded string asynchronously. It will throw an error if used to read a directory.

  function Deno.readTextFile(path: string | URL): Promise<string>

Below is the usage example.

  const text = await Deno.readTextFile('./hello.txt');
  console.log(text);

Using Deno.readTextFileSync

This function is similar to readTextFile, but it reads a file synchronously. It will throw an error if used to read a directory.

  function Deno.readTextFileSync(path: string | URL): string

Below is the usage example.

  const text = Deno.readTextFileSync('./hello.txt');
  console.log(text);

Using Deno.readFile

This function is used to read a file as an array of bytes. If the file contains text only, you can use TextDecoder to convert the result into a string. It will return empty data if used to read a directory.

 function Deno.readFile(path: string | URL): Promise<Uint8Array>

Below is the usage example.

  const decoder = new TextDecoder("utf-8");
  const data = await Deno.readFile('hello.txt');
  const text = decoder.decode(data);
  console.log(text);

Using Deno.readFileSync

This function is similar to readFile, but it reads a file synchronously. It will return empty data if used to read a directory.

  function Deno.readFileSync(path: string | URL): Uint8Array

Below is the usage example.

  const decoder = new TextDecoder("utf-8");
  const data = Deno.readFileSync('hello.txt');
  const text = decoder.decode(data);
  console.log(text);

Error Handling

Error can also happen when trying to read a file. For example, if the file doesn't exist.

  error: Uncaught (in promise) NotFound: No such file or directory (os error 2)
      at processResponse (core.js:223:11)
      at Object.jsonOpAsync (core.js:240:12)
      at async open (deno:cli/rt/30_files.js:44:17)
      at async Object.readFile (deno:cli/rt/40_read_file.js:15:18)
      at async file:///home/ivan/Projects/deno/src/examples/file_read.ts:8:14

Another common error is permission denied.

  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 open (deno:cli/rt/30_files.js:44:17)
      at async Object.readTextFile (deno:cli/rt/40_read_file.js:30:18)
      at async file:///home/ivan/Projects/deno/src/examples/file_read.ts:1:14

To handle the error, just wrap the code inside a try-catch block.

  try {
     const text = await Deno.readTextFile('./hello.txt');
    console.log(text);
  } catch (err) {
    console.error(err);
  }

 

That's how to write and read files using Deno. If your application needs to be able to read or write to files, the user who runs the application must have the required permissions. However, make sure not to give the user permissions to unnecessary files/directories or use a superuser to run the application.

 

Related Posts: