vue + electron 如何将文件写入磁盘

vue + electron how to write a file to disk

我正在使用 Vue 和 Electron 构建桌面应用程序。我想从 vue 组件保存一个文件,其中包含用户引入的一些数据。为此,我尝试在 vuex 操作中使用 fs 节点模块,但它让我出错。找不到那个模块。我知道 Vue 是客户端,但是,我认为在与 Electron 一起使用时它可以工作,但事实并非如此。为了初始化我的应用程序,我使用了 vue-cli 和命令 vue init webpack electron-vue。 我正在使用 vuex 系统并且也在使用 vuex 模块,我有一个 actions.js 文件,我在其中尝试使用 fs 模块:

// import * as fs from 'fs'; I used this way at first
const fs = require('fs');
export const writeToFile = ({commit}) => {
 fs.writeFileSync('/path/file.json', JSON.stringify(someObjectHere));
};

当我从 Vue 组件调用此操作时,例如,Options.vue,我使用 vuex 调度系统,并且在该组件的 created() 方法中:

this.$store.dispatch('writeToFile')

这引起了我上面提到的错误

要在 Vue 和 WebPack 中使用电子文件系统,文件系统实例必须在执行命令 "npm run build"[=12= 后在 dist/index.html 中声明]

<script>
    var fs = require('fs');
</script>

并且在vue组件中,使用fs就像在vue文件中声明一样。

...
export const writeToFile = ({commit}) => {
    fs.writeFileSync('/path/file.json', SON.stringify(someObjectHere))
};
...

而如果不在 electron 中使用它或者将它写入 dev 的索引中,则会抛出错误。

使用 window.require 会有帮助。这是“App.vue”文件的 <script></script> 部分:

import HelloWorld from './components/HelloWorld'

function writeToFileSync(filepath, content) {
  if (window && window.require) {
    const fs = window.require('fs')
    fs.writeFileSync(filepath, content)
  }
}

writeToFileSync('/usr/local/worktable/sandbox/msg.txt', 'Hello\nworld')

export default {
  name: 'App',

  components: {
    HelloWorld
  },

  data: () => ({
    //
  })
}

上面的代码是测试:

  • macOS 10.15
  • 电子 11(nodeIntegration 设置为真)
  • Vue 2.6.11(由 vue create 生成)