【问题标题】:Save file using VueJS and Electron使用 VueJS 和 Electron 保存文件
【发布时间】:2021-06-07 20:14:19
【问题描述】:

我想从分配给我的本地存储的文件中保存和加载 JSON。

这是我第一个使用 Electron 的项目。

这是我当前的代码,我收到此错误。 fs.readFileSync is not a function

<script>
import timer from "./components/Timer"
import fs from "fs"

export default {
  name: 'App',
  components: {
    timer
  },
  data() {
    console.log(fs.readFileSync("timer.json"))
    return {
      timerOptions: null
    }
  },
  created() {
    this.timerOptions = fs.readFileSync("./timer.json") // Here I want to load Data, but get the Error
    console.log(this.timerOptions)
  }
}
</script>

【问题讨论】:

  • 这看起来像是客户端的浏览器内代码。那里没有可用的“fs”。您需要在 main.js 中执行这些操作,afaik
  • 是的,VueJS 是客户端。但是 Electron 就像一个桌面应用程序,所以它必须以某种方式成为可能。
  • 当然可以,但是需要在主进程中进行,然后将结果发送给客户端:electronjs.org/docs/api/ipc-main
  • 如果我这样做了,我如何访问数据?这是我第一次使用电子
  • “访问数据”是什么意思?在 Vue 内部?你到底卡在哪里了?

标签: javascript node.js electron


【解决方案1】:

在主进程中,将保存到文件的函数写为:

import { ipcMain } from 'electron';
import fs from 'fs';

ipcMain.handle('export-file', async (event, {data}) => {
  return new Promise((resolve, reject) => {
    const stream = fs.createWriteStream(filePath, {
      encoding: 'utf-8',
    });
  ... save the data here
})

然后从你的 Vue 组件中调用它:

<script>
import { ipcRenderer } from 'electron';

export default {
  name: 'SaveFileComponent',

  methods: {
    async save() {
      const data = {}; // load it from your source            
      await ipcRenderer.invoke('export-file', {data});
    }
 }
}
</script>

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 2015-07-14
    • 2020-04-04
    • 2018-10-18
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2018-02-03
    • 2020-05-27
    相关资源
    最近更新 更多