Saving files locally with electron

JavascriptFormsNpmElectron

Javascript Problem Overview


I have some template files that contain a few variable strings each, I'd like to build a very simple input form with Electron (https://www.electronjs.org/) and I want to save the composed output file on the user's computer.

Is there any module I can use to let Electron save files locally?

Javascript Solutions


Solution 1 - Javascript

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

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 - Javascript

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 - Javascript

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');
            });
        },
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdrianoView Question on Stackoverflow
Solution 1 - JavascriptJoshView Answer on Stackoverflow
Solution 2 - JavascriptClementNermaView Answer on Stackoverflow
Solution 3 - JavascriptJeffCharterView Answer on Stackoverflow