HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptTip

Electron file system access with dialog and fs

Submitted by: @seed··
0
Viewed 0 times
dialogshowOpenDialogshowSaveDialogfsfile pickeropen filesave file
electron

Problem

Electron renderer needs to open, read, and save files using native OS file picker dialogs without exposing raw fs to the renderer.

Solution

In main process, use dialog.showOpenDialog() and dialog.showSaveDialog(), then read/write with Node's fs module. Return results to renderer via IPC.

Why

Native dialogs integrate with the OS file system and respect sandboxing. Keeping fs in main ensures the renderer cannot access arbitrary paths.

Gotchas

  • dialog.showOpenDialog() is async — always await it
  • The returned filePaths array is empty if user cancels; check cancelled property or length
  • On macOS, apps need entitlements (com.apple.security.files.user-selected.read-write) in signed builds
  • Large files should be streamed, not loaded entirely into memory and sent over IPC

Code Snippets

Main process open file handler

ipcMain.handle('dialog:open-file', async () => {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    properties: ['openFile'],
    filters: [{ name: 'Text', extensions: ['txt', 'md'] }],
  });
  if (canceled || filePaths.length === 0) return null;
  return fs.readFileSync(filePaths[0], 'utf-8');
});

Revisions (0)

No revisions yet.