Manos Kounelakis
Manos Kounelakis

Reputation: 3161

fs.writeFile creates read only file

I am writing an electron application and some times I need to save some text into a file.

I am using the dialog module to let the user choose where to save the file and hot to name the file. Here is the part of the code that handles the file creation:

var exportSettings = (event, settings) => {
        //settings is a css string 
        console.log(settings)
        dialog.showSaveDialog({
            title: 'Export settings as theme',
            filters: [{
                name: 'UGSM theme(CSS)',
                extensions: ['css']
            }]
        },(fileName) => {
            console.log('callback scope');
            console.log(fileName);
            if (fileName) {
                fs.writeFile(fileName, settings, (error) => {
                   console.log(error);
                });
            }
        });
    }

The file is being created after the user selects a directory and a file name.However it is created as read only and I would like it to be created as editable from everyone.Any ideas why this is happening?

Upvotes: 4

Views: 11265

Answers (1)

Manos Kounelakis
Manos Kounelakis

Reputation: 3161

Hey finally found the root cause of the problem

The problem lies on how I started my electron app. `

I use sudo electron . to start my app since it requires root access to perform some system tasks.Hence files created by sudo or root are read only to other users.To fix that I used chmod() to change permissions of file after it was created.

Here is my solution:

var exportSettings = (event, settings) => {
        dialog.showSaveDialog({
            title: 'Export settings as theme',
            filters: [{
                name: 'UGSM theme(CSS)',
                extensions: ['css']
            }]
        }, (fileName) => {
            if (fileName) {
                fs.writeFile(fileName, settings, (error) => {
                    //Since this code executes as root the file being created is read only.
                    //chmod() it
                    fs.chmod(fileName, 0666, (error) => {
                        console.log('Changed file permissions');
                    });
                });
            }
        });
    };

Upvotes: 2

Related Questions