Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Plugins and Native Features

Files and Dialogs in Tauri

Read and write files with the Tauri fs plugin, pick files with native dialogs, use base directories and scopes safely, and try runnable stand-ins of path resolution and filters.

A desktop app earns its place by working with the user's own files: opening a document, saving a project, exporting a report. A browser tab cannot do this freely, but Tauri can, through two official plugins. The fs plugin reads and writes files. The dialog plugin shows the operating system's own file pickers and message boxes.

You should know how plugins are added from The Tauri Plugin System. This lesson adds the two plugins, shows the JavaScript API, explains base directories, and connects it all to the permission scopes you will meet again in Scopes and Input Validation.

Real versus stand-in. The ts, rust and json blocks are real Tauri code. The runnable node blocks use an in-memory pretend file system to show path resolution and filtering. They do not touch your disk.

Setup

Terminal
npm run tauri add fs
npm run tauri add dialog
Rust
tauri::Builder::default()
    .plugin(tauri_plugin_fs::init())
    .plugin(tauri_plugin_dialog::init())
JSON
{
  "identifier": "main-capability",
  "windows": ["main"],
  "permissions": [
    "core:default",
    "dialog:default",
    "fs:allow-read-text-file",
    "fs:allow-write-text-file",
    "fs:allow-exists",
    "fs:allow-mkdir"
  ]
}

By default, the fs plugin only knows about a few app-specific locations. Reading C:\Users\you\Documents\secret.txt is refused until you explicitly allow it with a scope.

Reading and writing

TypeScript
import {
  readTextFile, writeTextFile, readDir, mkdir, exists, remove, BaseDirectory,
} from '@tauri-apps/plugin-fs';

await mkdir('notes', { baseDir: BaseDirectory.AppData, recursive: true });

await writeTextFile('notes/todo.txt', 'Write the report', {
  baseDir: BaseDirectory.AppData,
});

if (await exists('notes/todo.txt', { baseDir: BaseDirectory.AppData })) {
  const text = await readTextFile('notes/todo.txt', { baseDir: BaseDirectory.AppData });
  console.log(text);
}

const entries = await readDir('notes', { baseDir: BaseDirectory.AppData });
for (const entry of entries) {
  console.log(entry.name, entry.isFile, entry.isDirectory);
}

Besides text, there are readFile and writeFile for binary data (Uint8Array), copyFile, rename, stat, truncate, and open() for a file handle that reads in chunks, useful for large files so you never load them fully into memory. watch() and watchImmediate() report changes in a folder (they need the fs plugin's watch feature in Cargo).

Base directories

Instead of hard-coding C:\Users\Ada\AppData\Roaming\com.example.notes, you give a base directory and a relative path. Tauri resolves the real location for the current platform.

BaseDirectory Typical use
AppData Your app's persistent data (databases, saved projects)
AppConfig Settings files
AppCache Things you can recreate
AppLog Log files
Document, Download, Desktop, Picture User folders (need explicit scope)
Temp Scratch files

This keeps paths portable and also lets the permission system say "only below AppData".

Node.js Stand-in: resolving a base directory and a relative path

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.

The second line shows why base directories matter: a sneaky ../.. is detected and refused. Tauri does this kind of check for you, but you must never assume untrusted input is safe when you build paths in your own Rust commands.

Dialogs

The dialog plugin opens real operating system dialogs, which users trust and which return full file paths that are automatically added to the allowed scope for that session.

TypeScript
import { open, save, message, ask, confirm } from '@tauri-apps/plugin-dialog';
import { readTextFile, writeTextFile } from '@tauri-apps/plugin-fs';

// Open one file
const file = await open({
  multiple: false,
  directory: false,
  filters: [{ name: 'Markdown', extensions: ['md', 'markdown'] }],
});
if (file) {
  const text = await readTextFile(file);
}

// Save As
const target = await save({
  defaultPath: 'notes.md',
  filters: [{ name: 'Markdown', extensions: ['md'] }],
});
if (target) {
  await writeTextFile(target, 'Hello');
}

// Message boxes
await message('Saved!', { title: 'Notes', kind: 'info' });
const sure = await ask('Delete this note?', { title: 'Notes', kind: 'warning' });
const ok = await confirm('Close without saving?', { okLabel: 'Close', cancelLabel: 'Stay' });

open returns null if the user cancels, a string for a single pick, or an array for multiple: true. Always handle null: cancelling is a normal action, not an error. Dialogs from the JavaScript side are asynchronous and do not freeze the app.

Node.js Stand-in: file filters and cancel handling

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.

Filters are a convenience for users, not a security feature: still validate the content you read.

Scopes: allowing more than the defaults

When you really need the Documents folder, add a scope to a permission in the capability file:

JSON
{
  "identifier": "fs:allow-read-text-file",
  "allow": [{ "path": "$DOCUMENT/**" }]
}

Add a deny entry to protect part of an allowed tree, for example { "path": "$DOCUMENT/private/**" }. Deny always wins over allow. You can find out more in Capabilities and Permissions.

Common mistakes

  • Forgetting the baseDir and passing a relative path: it is then resolved against nothing meaningful.
  • Granting fs:default plus a broad ** scope "to make it work". Grant only the permissions you call.
  • Reading huge files with readTextFile. Use open() and read chunks.
  • Treating the user's cancel as an error.
  • Letting the frontend choose arbitrary paths for a Rust command. Validate in Rust too.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does open() from the dialog plugin return when the user presses Cancel?

    A cancelled dialog resolves with null. Handle it before using the result.
  2. 2. Why use BaseDirectory.AppData instead of a hard-coded path?

    Base directories make paths portable and give the permission system a clear root to allow or deny.
  3. 3. If a scope has both an allow and a deny entry that match a path, which wins?

    Deny rules always take precedence over allow rules in Tauri scopes.
  4. 4. Which approach suits a 2 GB log file best?

    A file handle lets you read part at a time so memory use stays small.

Summary

  • tauri-plugin-fs reads, writes, lists and watches files; tauri-plugin-dialog shows native pickers and message boxes.
  • Use BaseDirectory plus relative paths for portability and safe scopes.
  • Dialog results can be null; filters help users but do not replace validation.
  • Grant narrow permissions and scopes, with deny rules for sensitive subfolders.

Next: Store, SQL and Settings