G_T
G_T

Reputation: 1587

Electron Dialog not saving file

I am trying to follow this tutorial and it includes a section where a button is pressed. This opens a dialog window to save the contents of a text box as a text file. This is included in the main.js file. However when I run it the window opens but when I press save no file gets saved.

const ipcMain = require('electron').ipcMain
const fs = require('fs')
const { dialog } = require('electron')

ipcMain.on('clickedbutton', (event, data) => {

    dialog.showSaveDialog({ 
        filters: [{ name: 'text', extensions: ['txt'] }
        ]},function (fileName) {

            if(fileName === undefined) return
            fs.writeFile(fileName, data, function (err) {

            })

     });

})

I do not understand how the fileName argument is passed to the function. I then tried to separate the dialog window call and the function as suggested in this SO question but here fileName is an object which does not work.

ipcMain.on('clickedbutton',(event,data) => {

    var fileName = dialog.showSaveDialog({});

    fs.writeFile(fileName,data,function(err){});

})

What am I missing?

Upvotes: 0

Views: 1527

Answers (1)

Erick
Erick

Reputation: 1255

The tutorial you linked is outdated. The dialog functions changed in Electron 6, changing from a callback-based API (which you have in your code) to a promise-based one.

For Electron >= 6, you want to do the following inside an async function. Note that you can replace this function with dialog.showSaveDialogSync if you want to run the function synchronously.

  const { filePath, canceled } = await dialog.showSaveDialog({
    defaultPath: "text.txt"
  });

  if (filePath && !canceled) {
    const data = new Uint8Array(Buffer.from('Hello Node.js'));
    fs.writeFile(filePath, data, (err) => {
      if (err) throw err;
      console.log('The file has been saved!');
    });
  }

Note the option change from filters to defaultPath, since I'm assuming you want to set a default file name instead of rendering existing files that aren't text.txt unselectable by the dialog.

See a minimal example openable in Electron Fiddle. In this example, the dialog opens directly as the browser window open.

Upvotes: 2

Related Questions