Search code examples
vue.jselectronvuex

vue + electron how to write a file to disk


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


Solution

  • 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.