66

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?

Adriano
  • 3,788
  • 5
  • 32
  • 53
  • 2
    [fs](https://nodejs.org/api/fs.html)? – Zen Jun 28 '16 at 05:07
  • @Zen Is there any way to create multiple directories (i.e. `path/dir`, `path/dir2`, ...) with one command or is the only way to loop `mkdir`? – oldboy Oct 05 '19 at 06:30

3 Answers3

68

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.

vicke4
  • 2,973
  • 1
  • 20
  • 20
Josh
  • 3,225
  • 25
  • 22
  • 1
    I used app.getAppPath to create a file. You are not allowed to create files in the folder that hosts your electron app. – Johann Feb 12 '17 at 14:55
34

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.

ClementNerma
  • 1,079
  • 1
  • 11
  • 16
11
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');
            });
        },
    }
}
SeaWorld
  • 352
  • 3
  • 11
JeffCharter
  • 1,431
  • 17
  • 27
  • Excellent; thank you for this. I didn't realize Electron had these functions built-in. The new [File System Access API](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API) was lacking for my use case because I couldn't get the full selected path. – encryptedcurse Jul 09 '21 at 08:17