使用电子在本地保存文件
Saving files locally with electron
我有一些模板文件,每个模板文件都包含一些变量字符串,我想用 Electron (https://www.electronjs.org/) 构建一个非常简单的输入表单,我想将组合的输出文件保存在用户的计算机。
有什么模块可以让Electron在本地保存文件吗?
如果您的目标是多个平台,我回答 . Basically app.getPath(name), app.setPath(name, path), and app.getAppPath() 对于将文件保存到正确的位置非常有用,无论 OS。
您可能还想查看这些 Nodejs 包,它们有助于简化将文件直接保存到主机的过程...
如果您打算让用户保存文件,您也可以为此目的查看 Dialog api where you can specifically invoke a save dialog。
示例代码是:
const fs = require('fs');
try { fs.writeFileSync('myfile.txt', 'the text to write in the file', 'utf-8'); }
catch(e) { alert('Failed to save the file !'); }
您当然可以将文件名和内容名存储在变量中。
这会将内容保存在 myfile.txt
中,它位于当前工作目录中(您可以通过 process.cwd()
获取)。如果你想写,比方说在用户的主目录,你可以使用app.getPath
函数。
const {dialog} = require('electron').remote;
var fs = require('fs');
export default {
methods: {
save: function () {
var options = {
title: "Save file",
defaultPath : "my_filename",
buttonLabel : "Save",
filters :[
{name: 'txt', extensions: ['txt']},
{name: 'All Files', extensions: ['*']}
]
};
dialog.showSaveDialog(null, options).then(({ filePath }) => {
fs.writeFileSync(filePath, "hello world", 'utf-8');
});
},
}
}
我有一些模板文件,每个模板文件都包含一些变量字符串,我想用 Electron (https://www.electronjs.org/) 构建一个非常简单的输入表单,我想将组合的输出文件保存在用户的计算机。
有什么模块可以让Electron在本地保存文件吗?
如果您的目标是多个平台,我回答
您可能还想查看这些 Nodejs 包,它们有助于简化将文件直接保存到主机的过程...
如果您打算让用户保存文件,您也可以为此目的查看 Dialog api where you can specifically invoke a save dialog。
示例代码是:
const fs = require('fs');
try { fs.writeFileSync('myfile.txt', 'the text to write in the file', 'utf-8'); }
catch(e) { alert('Failed to save the file !'); }
您当然可以将文件名和内容名存储在变量中。
这会将内容保存在 myfile.txt
中,它位于当前工作目录中(您可以通过 process.cwd()
获取)。如果你想写,比方说在用户的主目录,你可以使用app.getPath
函数。
const {dialog} = require('electron').remote;
var fs = require('fs');
export default {
methods: {
save: function () {
var options = {
title: "Save file",
defaultPath : "my_filename",
buttonLabel : "Save",
filters :[
{name: 'txt', extensions: ['txt']},
{name: 'All Files', extensions: ['*']}
]
};
dialog.showSaveDialog(null, options).then(({ filePath }) => {
fs.writeFileSync(filePath, "hello world", 'utf-8');
});
},
}
}