Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 37 ยท Language and Runtime Basics

Reading and Writing Files

Read, write, append, copy, remove and list files in Deno with Deno.readTextFile, writeTextFile, open, readDir and stat. Handle errors, use streams for large files and grant permissions.

Reading and writing files is the first system task most programs do. Deno gives you short, promise-based functions for it on the Deno namespace, plus streaming access for big files. Because disk access is sensitive, every call needs the --allow-read or --allow-write permission (Permissions explains how to scope them).

The commands and Deno.* calls below are read-only because Deno is not installed on this site. The runnable examples use Node's fs/promises, whose functions have the same shape, so you can practise the patterns.

Reading a whole file

TypeScript
const text = await Deno.readTextFile("notes.txt");
console.log(text);

const bytes = await Deno.readFile("logo.png"); // Uint8Array
console.log(bytes.length);

Run it with permission to read only what it needs:

Terminal
deno run --allow-read=notes.txt,logo.png main.ts

Paths are relative to the current working directory, not to the script's folder. When you want a file that sits next to your source file, build the path from import.meta.dirname:

TypeScript
import { join } from "jsr:@std/path@1";

const file = join(import.meta.dirname!, "data", "users.json");
const users = JSON.parse(await Deno.readTextFile(file));

A path can also be a URL, which is the most portable way to say "next to this module":

TypeScript
const text = await Deno.readTextFile(new URL("./data.txt", import.meta.url));

Writing files

TypeScript
await Deno.writeTextFile("out.txt", "first line\n");
await Deno.writeTextFile("out.txt", "second line\n", { append: true });
await Deno.writeFile("bytes.bin", new Uint8Array([1, 2, 3]));

Options include append: true, create: false (fail if the file is missing), createNew: true (fail if it exists) and mode for Unix permissions. writeTextFile replaces the file's whole content by default, so be careful.

Try the same idea here with the Node.js equivalent. It writes into a temporary folder that is created and removed in the example.

Node.js Write, append and read back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Errors you should expect

A missing file, a folder where a file was expected, or missing permission each throw a different error class:

TypeScript
async function readOrDefault(path: string, fallback: string): Promise<string> {
  try {
    return await Deno.readTextFile(path);
  } catch (error) {
    if (error instanceof Deno.errors.NotFound) return fallback;
    throw error;
  }
}

Deno.errors.NotFound, AlreadyExists, PermissionDenied, NotCapable and IsADirectory are the usual ones, as covered in The Deno Namespace.

Files, folders and metadata

TypeScript
await Deno.mkdir("data/cache", { recursive: true });
await Deno.copyFile("a.txt", "b.txt");
await Deno.rename("b.txt", "c.txt");
await Deno.remove("data", { recursive: true });

const info = await Deno.stat("a.txt");
console.log(info.isFile, info.size, info.mtime);

const temp = await Deno.makeTempDir();

Deno.stat follows symlinks and Deno.lstat does not. A common check is "does this exist?". There is no exists function, because checking first creates a race condition. Instead, try the operation and handle NotFound.

Listing a directory

Deno.readDir returns an async iterable of entries:

TypeScript
for await (const entry of Deno.readDir("./src")) {
  const kind = entry.isDirectory ? "dir " : entry.isFile ? "file" : "link";
  console.log(kind, entry.name);
}

It is not recursive and does not sort. For walking a tree, @std/fs has walk, expandGlob and ensureDir (covered in Standard Library: Path, FS and Data).

Node.js List and filter a directory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Big files: streams

readTextFile loads everything into memory. For a 2 GB log file that is a problem. Open the file and read it as a stream, which processes it chunk by chunk:

TypeScript
using file = await Deno.open("big.log", { read: true });

const lines = file.readable
  .pipeThrough(new TextDecoderStream())
  .pipeThrough(new TextLineStream()); // from @std/streams

let errors = 0;
for await (const line of lines) {
  if (line.includes("ERROR")) errors++;
}
console.log(`${errors} error lines`);

The using keyword closes the file automatically when the block ends, so you never leak file descriptors. Streams are the topic of URL, Streams and Encoding.

The core of "turn chunks into lines" is simple logic that you can run on its own:

Node.js Chunks to lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Safer writes

Writing straight into the target file risks leaving it half-written if the program crashes. The standard fix is write to a temp file, then rename:

TypeScript
async function writeAtomic(path: string, data: string): Promise<void> {
  const temp = `${path}.tmp-${crypto.randomUUID()}`;
  await Deno.writeTextFile(temp, data);
  await Deno.rename(temp, path);
}

A rename on the same filesystem replaces the destination in one step, so readers see the old file or the new one, never half of each.

Synchronous versions

Every function has a Sync twin: Deno.readTextFileSync, Deno.writeTextFileSync, and so on. They block the event loop, which is fine in a short script or at startup, and wrong in a server that handles requests. In doubt, use the async version.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which permission lets a program call Deno.readTextFile?

    Reading files needs --allow-read, optionally limited to certain paths.
  2. 2. How do you build a path to a file next to the current module?

    Relative strings resolve against the working directory; a URL based on import.meta.url resolves against the module.
  3. 3. Why is there no Deno.exists function?

    The file can change between the check and the use, so try the operation and catch NotFound.
  4. 4. What does the using keyword do with an open file?

    using disposes the resource, closing the file, when the scope ends.

Summary

  • Deno.readTextFile, readFile, writeTextFile and writeFile cover most needs; each needs --allow-read or --allow-write.
  • Paths are relative to the working directory; use import.meta.dirname or a URL for module-relative paths.
  • Handle Deno.errors.NotFound rather than checking existence first.
  • Deno.readDir lists a folder; Deno.stat gives metadata.
  • Stream large files with Deno.open and using.
  • Write atomically with a temp file and a rename.

Next: Command-Line Arguments and Environment Variables