Javascript 使用电子在本地保存文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38067298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:02:46  来源:igfitidea点击:

Saving files locally with electron

javascriptformsnpmelectron

提问by Adriano

I have some template files that contain a few variable strings each, I'd like to build a very simple input form with Electron (http://electron.atom.io/) and I want to save the composed output file on the user's computer.

我有一些模板文件,每个文件都包含几个变量字符串,我想用 Electron ( http://electron.atom.io/)构建一个非常简单的输入表单,并且我想将合成的输出文件保存在用户的计算机。

Is there any module I can use to let Electron save files locally?

我可以使用任何模块让 Electron 在本地保存文件吗?

回答by Josh

If you are targeting multiple platforms, I answered a similar question here. Basically app.getPath(name), app.setPath(name, path), and app.getAppPath()are very useful in saving files to the the right place regardless of the OS.

如果您针对多个平台,我在这里回答了一个类似的问题。基本上app.getPath(name)app.setPath(name, path)app.getAppPath()在将文件保存到正确位置方面非常有用,而不管操作系统如何。

You may also want to check out these Nodejs packages which help simplify saving files directly to the host machine...

您可能还想查看这些 Nodejs 包,它们有助于简化将文件直接保存到主机的过程...

If you intend for users to save files you might also have a look at the Dialog apiwhere you can specifically invoke a save dialogfor that purpose.

如果您打算让用户保存文件,您还可以查看Dialog api,您可以在其中专门为此目的调用保存对话框

回答by ClementNerma

A sample code is :

示例代码是:

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 !'); }

You can of course store the file's name as well as the content's name in variables.

您当然可以将文件名和内容名存储在变量中。

This will save the content in myfile.txt, which is located inside the current working directory (which you can get through process.cwd()). If you want to write, let's say in the user's home directory, you can use the app.getPathfunction.

这会将内容保存在 中myfile.txt,该目录位于当前工作目录(您可以通过process.cwd())内。如果要写入,假设在用户的主目录中,您可以使用该app.getPath功能。

回答by JeffCharter

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( options, (filename) => {
          fs.writeFileSync(filename, "hello world", 'utf-8');
        })
      },
    }