使用 VueJS 和 Electron 保存文件

Save file using VueJS and Electron

我想从分配到本地存储的文件中保存和加载 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>

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

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>