Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Native APIs and Files

Native Dialogs and Working with Files

Open and save files in an Electron app with native dialogs and Node's fs module, keep file access in the main process, and handle errors, large files and recent documents.

A desktop app earns its place by doing things a web page cannot: opening a document from anywhere on disk, saving it back, and letting the operating system show its own familiar file picker. Electron gives you both halves. The dialog module shows native open, save and message boxes, and Node's fs module reads and writes the chosen files.

In this lesson you build the standard "open, edit, save" pipeline. You will see why file access belongs in the main process, how a renderer asks for it safely through IPC, and how to deal with the failures real users hit: cancelled dialogs, missing files, permission errors and huge files.

Electron itself cannot run in our editor, so the real main-process code is shown read-only. The runnable examples are small stand-ins written in plain Node.js that reproduce the logic around it: results of a dialog, safe reads and atomic writes.

The dialog module

dialog lives in the main process. Its methods return promises, so you await the user's choice.

JavaScript
// main.js
import { app, BrowserWindow, dialog, ipcMain } from 'electron';
import { readFile, writeFile } from 'node:fs/promises';

ipcMain.handle('file:open', async (event) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  const { canceled, filePaths } = await dialog.showOpenDialog(win, {
    title: 'Open a text file',
    properties: ['openFile'],
    filters: [
      { name: 'Text', extensions: ['txt', 'md'] },
      { name: 'All files', extensions: ['*'] },
    ],
  });
  if (canceled) return null;
  const path = filePaths[0];
  return { path, text: await readFile(path, 'utf8') };
});

Three details matter here:

  • Pass the parent window as the first argument. The dialog then becomes a sheet or modal tied to that window instead of floating free.
  • Always check canceled. When the user presses Escape, filePaths is an empty array and the save dialog's filePath is undefined.
  • Filters use extensions without a dot. The special '*' shows everything.

The save dialog is the mirror image. It returns a path that may not exist yet, so it is your job to write the file.

JavaScript
ipcMain.handle('file:save', async (event, { path, text }) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  let target = path;
  if (!target) {
    const result = await dialog.showSaveDialog(win, {
      defaultPath: 'untitled.txt',
      filters: [{ name: 'Text', extensions: ['txt'] }],
    });
    if (result.canceled) return null;
    target = result.filePath;
  }
  await writeFile(target, text, 'utf8');
  return target;
});

Other useful options: properties: ['openFile', 'multiSelections'] to choose several files, ['openDirectory'] to choose a folder, and ['createDirectory'] on macOS to allow "New Folder" in the picker.

Message boxes

For quick questions use dialog.showMessageBox. It returns the index of the pressed button, so you map answers yourself.

JavaScript
const { response } = await dialog.showMessageBox(win, {
  type: 'warning',
  message: 'Save changes before closing?',
  detail: 'Your changes will be lost if you do not save them.',
  buttons: ['Save', 'Discard', 'Cancel'],
  defaultId: 0,
  cancelId: 2,
});

cancelId is the button index returned when the user dismisses the dialog with Escape or the close button. Without it you get the first button's index on some platforms, which is how apps accidentally "save" a file the user wanted to abandon.

The flow between processes

The renderer has no fs and no dialog. It asks, the main process does the work, and returns plain data.

sequenceDiagram
  participant R as Renderer
  participant P as Preload
  participant M as Main process
  participant OS as OS dialog and disk
  R->>P: window.files.open()
  P->>M: ipcRenderer.invoke('file:open')
  M->>OS: showOpenDialog
  OS-->>M: chosen path
  M->>OS: readFile
  OS-->>M: text
  M-->>R: path and text

Only the main process touches the operating system. The renderer receives a path and the text.

The preload script exposes exactly two functions and nothing else:

JavaScript
// preload.js
import { contextBridge, ipcRenderer } from 'electron';

contextBridge.exposeInMainWorld('files', {
  open: () => ipcRenderer.invoke('file:open'),
  save: (doc) => ipcRenderer.invoke('file:save', doc),
});

A stand-in for the open flow

The first runnable example reproduces what the handler does around the dialog: treat a cancel as null, read the file, and turn failures into readable messages instead of stack traces. The "dialog" is a plain function that either returns a path or cancels.

Node.js Open handler with cancel and error 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.

The renderer never sees an exception object. It gets { ok: false, reason }, which is easy to show in the interface and safe to send over IPC.

Saving without corrupting the file

writeFile truncates the target first and then writes. If the app crashes or the disk fills halfway through, the user's document is half gone. The professional pattern is an atomic save: write a temporary file next to the target, then rename it over the original. A rename within one folder is atomic on every platform Electron supports.

Node.js Atomic save with a temporary file

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.

After both saves only note.txt remains. The temporary file never survives a successful save, and a failed save leaves the old content untouched.

Large files and recent documents

readFile loads everything into memory, which is fine for notes but wrong for a 2 GB log. For big files read in chunks with createReadStream, or open a handle and read a slice, and send the renderer one page at a time.

Electron also integrates with the OS "recent files" list:

JavaScript
app.addRecentDocument(path);       // macOS Dock menu and Windows Jump List
app.clearRecentDocuments();

Add the file after every successful open or save. On macOS, app.on('open-file', ...) fires when a user double-clicks a document associated with your app, so listen for it before the app is ready.

Mistakes to avoid

  • Trusting a renderer-supplied path. If a handler reads ipcMain.handle('read', (e, path) => readFile(path)), any compromised page can read ~/.ssh/id_rsa. Prefer handlers that open a dialog themselves, or check that the path sits under an allowed folder (see Validating IPC and Handling Secrets).
  • Forgetting canceled. Destructuring filePaths[0] of an empty array gives undefined, and readFile(undefined) throws.
  • Blocking the main process with readFileSync on big files. The whole app freezes because the main process also drives windows and menus.
  • Hard-coded path separators. Build paths with node:path, never by joining strings with / or \.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In which process should dialog.showOpenDialog and fs.readFile run?

    dialog and fs are Node and Electron main-side APIs. The renderer asks for them through IPC and receives plain data, which keeps the sandboxed page powerless.
  2. 2. What does showOpenDialog return when the user presses Escape?

    The promise resolves normally with canceled set to true. Handlers must check it before using filePaths[0].
  3. 3. Why save by writing a temporary file and then renaming it?

    writeFile truncates the target before writing. With a temp file plus rename the target is either the old complete version or the new complete version, never a mix.
  4. 4. What is the purpose of cancelId in showMessageBox?

    When the user closes the box with Escape or the window button, the result is the cancelId button index, so you can treat it as a real Cancel.

Summary

  • dialog and fs belong in the main process; the renderer gets them only through narrow IPC handlers.
  • Pass the parent window to dialogs and always check canceled.
  • Return { ok, reason } style results instead of raw exceptions.
  • Save atomically with a temporary file and rename.
  • Stream large files and register recent documents with app.addRecentDocument.

Next: Clipboard, Notifications and the Shell