Read and write files

Concepts

Overview

Interacting with the filesystem to read and write files is a common requirement. Deno provides a number of ways to do this via the standard library and the Deno runtime API.

As highlighted in the Fetch Data example Deno restricts access to Input / Output by default for security reasons. Therefore when interacting with the filesystem the --allow-read and --allow-write flags must be used with the deno run command.

Reading a text file

The Deno runtime API makes it possible to read text files via the Deno.readTextFile() method, it just requires a path string or URL object. The method returns a promise which provides access to the file’s text data.

Command: deno run --allow-read read.ts

  1. /**
  2. * read.ts
  3. */
  4. const text = await Deno.readTextFile("./people.json");
  5. console.log(text);
  6. /**
  7. * Output:
  8. *
  9. * [
  10. * {"id": 1, "name": "John", "age": 23},
  11. * {"id": 2, "name": "Sandra", "age": 51},
  12. * {"id": 5, "name": "Devika", "age": 11}
  13. * ]
  14. */

Writing a text file

The Deno runtime API allows developers to write text to files via the Deno.writeTextFile() method. It just requires a file path and text string. The method returns a promise which resolves when the file was successfully written.

To run the command the --allow-write flag must be supplied to the deno run command.

Command: deno run --allow-write write.ts

  1. /**
  2. * write.ts
  3. */
  4. await Deno.writeTextFile("./hello.txt", "Hello World!");
  5. console.log("File written to ./hello.txt");
  6. /**
  7. * Output: File written to ./hello.txt
  8. */

By combining Deno.writeTextFile and JSON.stringify you can easily write serialized JSON objects to a file. This example uses synchronous Deno.writeTextFileSync, but this can also be done asynchronously using await Deno.writeTextFile.

To execute the code the deno run command needs the write flag.

Command: deno run --allow-write write.ts

  1. /**
  2. * write.ts
  3. */
  4. function writeJson(path: string, data: object): string {
  5. try {
  6. Deno.writeTextFileSync(path, JSON.stringify(data));
  7. return "Written to " + path;
  8. } catch (e) {
  9. return e.message;
  10. }
  11. }
  12. console.log(writeJson("./data.json", { hello: "World" }));
  13. /**
  14. * Output: Written to ./data.json
  15. */