Saving files locally with electron

Solution 1:

If you are targeting multiple platforms, I answered a similar question here. Basically app.getPath(name), app.setPath(name, path), and app.getAppPath() are very useful in saving files to the the right place regardless of the OS.

You may also want to check out these Nodejs packages which help simplify saving files directly to the host machine...

  • fs-jetpack
  • graceful-fs
  • Node.js fs

If you intend for users to save files you might also have a look at the Dialog api where you can specifically invoke a save dialog for that purpose.

Solution 2:

A sample code is :

const fs = require('fs');
try { fs.writeFileSync('myfile.txt', 'the text to write in the file', 'utf-8'); }
catch(e) { alert('Failed to save the file !'); }

You can of course store the file's name as well as the content's name in variables.

This will save the content in myfile.txt, which is located inside the current working directory (which you can get through process.cwd()). If you want to write, let's say in the user's home directory, you can use the app.getPath function.

Solution 3:

const {dialog} = require('electron').remote;
var fs = require('fs');

export default {
    methods: {
        save: function () {
            var options = {
                title: "Save file",
                defaultPath : "my_filename",
                buttonLabel : "Save",

                filters :[
                    {name: 'txt', extensions: ['txt']},
                    {name: 'All Files', extensions: ['*']}
                ]
            };

            dialog.showSaveDialog(null, options).then(({ filePath }) => {
                fs.writeFileSync(filePath, "hello world", 'utf-8');
            });
        },
    }
}