vue + electron how to write a file to disk

前端 未结 2 1806
一生所求
一生所求 2021-02-06 15:21

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

相关标签:
2条回答
  • 2021-02-06 15:51

    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)
    0 讨论(0)
  • 2021-02-06 16:07

    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 讨论(0)
提交回复
热议问题