4
votes

I'm building a desktop app using Vue and Electron. I want to save a file from a vue component with some data introduced by the user. For doing that, I tried used fs node module inside an vuex action, but it got me error. Can't found that module. I know Vue is client side, but, I thought that at the moment of using with Electron it could work, but it does't. To init my app I used vue-cli and the command vue init webpack electron-vue. I'm using vuex system and using vuex modules too, I've an actions.js file where I tried to use the fs module:

// 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));
};

When I call this action from a Vue component, ex, Options.vue, I use the vuex dispatch system, and, in the created() method of that component:

this.$store.dispatch('writeToFile')

That's raised me the error above mentioned

2

2 Answers

0
votes

to use File System in electron with Vue and WebPack, the file system instance has to be declared in the dist/index.html after execute the command "npm run build"

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

and in the vue component, it 's used fs like if it would have been declared in the vue file.

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

while if not use it in electron or you write it in the index to dev, it throws an error.

0
votes

Using window.require will help. This is the <script></script> part of the "App.vue" file:

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: () => ({
    //
  })
}

The code above is test on:

  • macOS 10.15
  • Electron 11 (with nodeIntegration set to true)
  • Vue 2.6.11 (generated by vue create)