我正在尝试关注this tutorial它包括按下按钮的部分。这将打开一个对话框窗口,将文本框的内容保存为文本文件。它包含在 main.js
文件中。但是,当我运行它时,窗口会打开,但是当我按“保存”时,不会保存任何文件。
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) {
})
});
})
我不明白 fileName
参数如何传递给函数。然后我尝试将对话框窗口调用和建议的函数分开 in this SO question但这里 fileName 是一个不起作用的对象。
ipcMain.on('clickedbutton',(event,data) => {
var fileName = dialog.showSaveDialog({});
fs.writeFile(fileName,data,function(err){});
})
我错过了什么?
最佳答案
您链接的教程已过时。 Electron 6 中的 dialog
函数发生了变化,从基于回调的 API(代码中具有)更改为基于 Promise 的 API。
对于 Electron >= 6,您希望在 async
函数内执行以下操作。请注意,如果您想同步运行该函数,可以用 dialog.showSaveDialogSync
替换该函数。
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!');
});
}
请注意选项从 filters
更改为 defaultPath
,因为我假设您想要设置默认文件名,而不是渲染非 的现有文件>text.txt
无法通过对话框选择。
查看minimal example可在 Electron Fiddle 中打开。在此示例中,该对话框会在浏览器窗口打开时直接打开。
关于javascript - Electron 对话框不保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61161341/