Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: A File Organizer with Folder Watching

Build an Electron file organizer: choose a folder, watch it for new files, classify them by rules, preview a plan, move files safely with undo, and report progress to the interface.

The third project is a file organizer. The user picks their Downloads folder and defines rules: images go to Pictures/, PDFs to Documents/, archives to Archives/. The app watches the folder and files itself, or shows a preview of what it would do and applies it on request, with an undo.

It is a good project because file moving is dangerous. You can overwrite a file, lose one, or move something the user was still using. The design therefore centres on three habits: plan before acting, never overwrite, and remember how to undo. All three live in plain modules you can run right here.

Architecture

flowchart TD
  W["Watcher (fs.watch or chokidar)"] --> D["Debounce and wait until file is stable"]
  D --> P["Planner: apply rules, produce a plan"]
  P --> V["Preview in the UI"]
  V -->|approve| E["Executor: move without overwriting, log every move"]
  E --> U["Undo journal"]
  U -->|undo| E

The planner is pure; only the executor touches the disk.

Choosing the folder

The renderer never receives a free path. The main process opens the dialog and keeps the chosen root, and every later operation is checked against it.

JavaScript
ipcMain.handle('folder:choose', async (event) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  const { canceled, filePaths } = await dialog.showOpenDialog(win, { properties: ['openDirectory'] });
  if (canceled) return null;
  root = filePaths[0];
  startWatching(root);
  return root;
});

See Native Dialogs and Files for the dialog details and Validating IPC and Handling Secrets for why every path must stay inside root.

Watching

Node's fs.watch is built in but behaves differently on each platform (duplicate events, missing file names, no recursion on some Linux setups). For production use chokidar, which normalises all that. Either way the same two problems appear:

  1. Event bursts. One download can fire several events. Debounce per file.
  2. Half-written files. A file in Downloads may still be downloading. Wait until its size stops changing, and ignore temporary names such as .crdownload and .part.
JavaScript
import { watch } from 'node:fs';

const w = watch(root, (eventType, filename) => {
  if (!filename) return;
  scheduleCheck(join(root, filename));
});

Stable-file detection

This runnable example simulates a growing file and a function that waits until the size is unchanged for a short period before declaring it ready.

Node.js Waiting for a file to finish writing

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 planner: pure rules

Rules map a file to a destination folder. They are data, so users can edit them, and the planner is a pure function: the same input always gives the same plan, with no disk access, which makes it trivial to test and safe to preview.

Node.js A rule-based planner

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 preview window of the app shows exactly this list. Nothing has moved yet. The user can untick rows and then press Apply.

The executor with a journal

The executor performs each move and appends to a journal: where each file came from and where it went. Undo reads the journal backwards. Key safety measures: refuse to overwrite, and create the destination folder first.

Node.js Moving files with an undo journal

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 conflicting a.pdf was skipped, not overwritten, and undo only restores files that were actually moved. A real app would also offer to rename the conflicting file and would persist the journal to disk so undo survives a restart (App Data and Settings).

Reporting progress to the window

Long operations should stream progress. The main process sends events; the renderer subscribes through the preload bridge.

JavaScript
// main.js
for (const [i, m] of moves.entries()) {
  await moveOne(m);
  win.webContents.send('organize:progress', { done: i + 1, total: moves.length, name: m.from });
}
JavaScript
// preload.js
contextBridge.exposeInMainWorld('organizer', {
  plan: (root) => ipcRenderer.invoke('organize:plan', root),
  apply: (ids) => ipcRenderer.invoke('organize:apply', ids),
  undo: () => ipcRenderer.invoke('organize:undo'),
  onProgress: (cb) => {
    const listener = (_e, data) => cb(data);
    ipcRenderer.on('organize:progress', listener);
    return () => ipcRenderer.off('organize:progress', listener);   // unsubscribe: no leaks
  },
});

Returning the unsubscribe function is the leak-proof pattern from Memory and Debugging.

Safety rules for any file tool

  1. Operate only inside the folder the user chose; resolve and check containment.
  2. Show a plan first; apply only after approval, or after a clearly labelled "automatic" setting.
  3. Never overwrite and never delete. Prefer moving to the OS trash with shell.trashItem.
  4. Keep a journal and offer undo.
  5. Ignore temporary and hidden files; wait for files to settle.
  6. Handle errors per file so one locked file does not abort the batch.

Extend it

  • User-defined rules in a settings file, validated like the settings store.
  • Rules by date or by content (images by EXIF date into Pictures/2024/05).
  • A tray icon with a pause toggle and a "last organised" notification.
  • A dry-run command-line mode that reuses the same planner module.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the planner a pure function with no disk access?

    A pure planner gives the same plan for the same input and cannot damage files, so it powers the preview and the tests.
  2. 2. Why wait until a file's size stops changing before moving it?

    Moving a half-written file corrupts it or breaks the writer. Stability detection and ignoring .part or .crdownload names avoid that.
  3. 3. What does the undo journal record?

    With the from and to of each successful move, undo can reverse them in the opposite order.
  4. 4. How should the executor handle a destination file that already exists?

    Never destroy user data. Skip the move or choose a free name like 'name (1).pdf'.

Summary

  • Choose the folder in the main process and confine every operation to it.
  • Watch with debouncing and stable-file detection; ignore temporary files.
  • Separate a pure planner (rules produce a plan) from an executor that moves safely and records a journal.
  • Never overwrite or delete; offer preview, progress and undo.
  • Return an unsubscribe function from event listeners exposed in the preload.

Next: Electron Practice Set and Interview Questions