Electron Local Files and System Interaction

Use file dialogs, asynchronous file APIs, and common system capabilities to work safely with local files.

🎯 Introduction

This article implements one feature: click a button to select a .txt file and display its contents on the page.

By the end of this article, you will be able to:

  • Open the system file picker with dialog.showOpenDialog.
  • Get the path selected by the user.
  • Read a text file with readFile.
  • Display the filename and contents on the page.

🧱 Selecting a file and reading it are separate operations

Selecting a file and reading it are two distinct operations:

OperationAPIResult
Select a filedialog.showOpenDialogFile path
Read a filereadFileFile contents

showOpenDialog only lets the user choose a file; it does not read the contents. After obtaining the path, pass it to readFile.

Both operations belong in main.js. The page only calls openTextFile() from the preload script, without accessing Electron or Node.js modules directly.


🛠 Select and read a file in the main process

Below is the complete main.js. Replace the original file rather than appending this code to it.

Register each channel only once. Keep just one ipcMain.handle('file:open-text', ...) in main.js; otherwise, Electron reports Attempted to register a second handler.
main.js
const { app, BrowserWindow, dialog, ipcMain } = require('electron/main');
const { readFile } = require('node:fs/promises');
const path = require('node:path');

function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
        },
    });

    win.loadFile(path.join(__dirname, 'index.html'));
}

async function openTextFile() {
    const result = await dialog.showOpenDialog({
        title: 'Select a text file',
        properties: ['openFile'],
        filters: [
            {
                name: 'Text files',
                extensions: ['txt'],
            },
        ],
    });

    if (result.canceled || result.filePaths.length === 0) {
        return null;
    }

    const filePath = result.filePaths[0];
    const content = await readFile(filePath, 'utf8');

    return {
        name: path.basename(filePath),
        content,
    };
}

app.whenReady().then(() => {
    ipcMain.handle('file:open-text', openTextFile);
    createWindow();

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

First, look at the dialog options:

  • properties: ['openFile']: Allow file selection only.
  • extensions: ['txt']: Show only .txt files.
  • result.canceled: Indicate whether the user canceled selection.
  • result.filePaths[0]: The first path selected by the user.

After obtaining the path, this line reads the file contents:

const content = await readFile(filePath, 'utf8');

'utf8' reads the text using UTF-8 encoding. path.basename(filePath) extracts the filename from the full path.

File pickers can look different on Windows, macOS, and Linux. Their appearance depends on the current operating system.

🌉 Expose openTextFile to the page

Now that main.js can select and read a file, expose a method to the page in preload.js:

preload.js
const { contextBridge, ipcRenderer } = require('electron/renderer');

contextBridge.exposeInMainWorld('electronAPI', {
    openTextFile: () => ipcRenderer.invoke('file:open-text'),
});

The page can then call:

window.electronAPI.openTextFile();

This requests the handler for the matching file:open-text channel in main.js and waits for the file data.

Expose only openTextFile() here. Do not expose the entire ipcRenderer or fs module to the page.

🖥 Prepare the page

Add a button and elements for the filename and contents to index.html:

index.html
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta
            http-equiv="Content-Security-Policy"
            content="default-src 'self'; script-src 'self'"
        />
        <title>Text file preview</title>
    </head>
    <body>
        <h1>Text file preview</h1>
        <button id="open-file" type="button">Choose file</button>
        <p id="file-name">No file selected</p>
        <pre id="file-content"></pre>

        <script src="./renderer.js"></script>
    </body>
</html>

The pre element preserves line breaks and spaces, making it suitable for previewing plain text files.


🖱 Handle the button click and display the contents

Finally, handle the button click in renderer.js:

renderer.js
const openButton = document.querySelector('#open-file');
const fileName = document.querySelector('#file-name');
const fileContent = document.querySelector('#file-content');

openButton.addEventListener('click', async () => {
    try {
        const file = await window.electronAPI.openTextFile();

        if (!file) {
            fileName.textContent = 'Selection canceled';
            return;
        }

        fileName.textContent = file.name;
        fileContent.textContent = file.content;
    } catch (error) {
        console.error('Failed to read file:', error);
        fileName.textContent = 'Failed to read file';
        fileContent.textContent = '';
    }
});

Handle three possible outcomes:

  • The user selects a file: display its name and contents.
  • The user cancels: display “Selection canceled”.
  • Reading fails: display an error message.

Display file contents with textContent. Even if the text contains HTML tags, they appear as plain text.

Run the project:

npm start

Click “Choose file” and select a UTF-8-encoded .txt file. The page displays its name and contents.


🪤 Common problems

Attempted to register a second handler

This means file:open-text was registered more than once in main.js. Search for that channel and keep only one ipcMain.handle. Replacing the old file with the complete main.js above avoids duplicate registration.

Clicking the button does nothing

First check that BrowserWindow correctly configures preload.js:

main.js
const win = new BrowserWindow({
    webPreferences: {
        preload: path.join(__dirname, 'preload.js'),
    },
});

Also confirm that the preload script and main process use the same channel name: file:open-text.

Why is there no file data after cancellation?

Cancellation is a normal operation. openTextFile() returns null; the page can check !file and return immediately.

Why are Markdown files missing?

The current filters includes only txt. To also select Markdown files, change it to:

extensions: ['txt', 'md'],

Omit the dot in an extension: use 'md', not '.md'.

Why is Chinese text garbled?

This example reads files as UTF-8. If the source file uses another encoding, convert it to UTF-8 first or use the appropriate decoder.


🧾 Summary

  • showOpenDialog opens the system file picker.
  • showOpenDialog returns paths without reading files automatically.
  • readFile(filePath, 'utf8') reads text contents.
  • Cancellation should end normally without displaying an error.
  • The preload script exposes only the specific openTextFile() method.
  • The page displays file contents with textContent.

❓ Questions and answers

Q1: Why is filePaths an array?

showOpenDialog supports multiple selection. This article selects only one file, so it reads the first element.

Q2: Does filters guarantee that a file contains text?

No. It filters by extension and does not inspect the file's contents.

Q3: Why pass utf8 to readFile?

We are reading text. Specifying utf8 makes the return value a string.

Q4: Why does dialog belong in main.js?

dialog is a main process module and cannot be used directly in an ordinary page script.


🧪 Practice

Exercise 1: Let the file picker accept both .txt and .md files.

filters: [
    {
        name: 'Text files',
        // Write your code here
    },
],

Exercise 2: After successfully reading a file, set the page title to its filename.

renderer.js
if (file) {
    // Write your code here
}

🎉 You have implemented text file selection and reading in Electron!