showSaveDialog and showSaveDialogSync in Electron Js

  • The dialog.showSaveDialog and dialog.showSaveDialogSync functions in Electron.js are used to display native operating system dialogs for saving files. Here's a brief explanation of these functions:
  • dialog.showSaveDialog: This is an asynchronous method that opens a save dialog, allowing the user to choose the path and name of the file they want to save. It returns a promise that resolves to an object containing information about the chosen file path. You can handle the result using the promise's `.then()` and `.catch()` methods. Once the user confirms the file selection, you can use the chosen path to save the file.
  • dialog.showSaveDialogSync: This is a synchronous version of `showSaveDialog`. It blocks the execution of your code until the user selects a file path or cancels the dialog. It returns an object containing information about the chosen file path directly. It is simpler to use but should be used with caution since it can freeze the application's user interface until the dialog is closed.
  • Both functions take an options object as a parameter, allowing you to customize the behavior and appearance of the save dialog. The options can include properties such as the dialog's title, button labels, default path, file filters, and more.
  • When the user selects a file path and confirms the save, you can use the chosen path to save the file content using Node.js's file system methods like `fs.writeFile()` or any other relevant method for your specific use case.


    const { app, BrowserWindow, dialog } = require('electron');
    const fs = require('fs');

    // Example content to be saved
    const contentToSave = 'Hello, World!';

    function createWindow() {
        let win = new BrowserWindow({
            width: 800,
            height: 600,
            webPreferences: {
                nodeIntegration: true,
                contextIsolation: false,
                enableRemoteModule: true
            }
        });
        win.webContents.openDevTools();
        win.loadFile('public/index.html');

        setTimeout(() => {
            dialog.showSaveDialog({
                title: 'Save File', // Title of the save dialog
                defaultPath: "C:\\Users\\gagan\\OneDrive\\Pictures\\Screenshots",
                buttonLabel: 'Save', // Label for the save button
                filters: [
                    { name: 'Text Files', extensions: ['txt'] }, // Filter for specific file type
                    { name: 'All Files', extensions: ['*'] } // Filter for all file types
                ],
                properties: [
                    'showHiddenFiles'
                    // 'dontAddToRecent',
                ]
            }).then(result => {
                if (!result.canceled && result.filePath) {
                    const savePath = result.filePath;

                    // Write the content to the selected file
                    fs.writeFile(savePath, contentToSave, 'utf-8', (err) => {
                        if (err) {
                            console.error('Error saving file:', err);
                        } else {
                            console.log('File saved successfully!');
                        }
                    });
                } else {
                    console.log("Dialog canceled by user")
                }
            }).catch(err => {
                console.log("err", err)
            })
        }, 2000);
    }

    app.on('ready', () => {
        createWindow()
    });

  • In this example, the dialog.showSaveDialog method is used to display a save dialog to the user. The options object provides the title, button label, and filters for specifying the file type.
  • When the save dialog is confirmed and a file path is chosen, the selected file path is obtained from the result. The content to be saved (in this case, the string "Hello, World!") is then written to the selected file using the fs.writeFile method.
  • If there are any errors during the saving process, an error message is logged to the console. Otherwise, a success message is logged.
  • You can adapt this example to your specific use case, such as dynamically generating content to save or handling the save event in your Electron application.
  • By utilizing `showSaveDialog` or `showSaveDialogSync`, you can provide a native and familiar file saving experience to users in your Electron application.

No comments:

Post a Comment