【问题标题】:fs.writeFile creates read only filefs.writeFile 创建只读文件
【发布时间】:2017-12-21 09:07:37
【问题描述】:

我正在编写一个电子应用程序,有时我需要将一些文本保存到一个文件中。

我正在使用对话框模块让用户选择保存文件的位置并热命名文件。 以下是处理文件创建的部分代码:

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

在用户选择目录和文件名后创建该文件。但是它被创建为只读的,我希望它被创建为每个人都可以编辑。任何想法为什么会发生这种情况?

【问题讨论】:

  • 您知道问题是尝试访问该文件的用户的文件权限之一还是因为该文件设置为对所有人只读? fs.writeFile() 函数接受一些影响文件的标志。你有没有探索过这个选择?其中许多标志都记录在这里:nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback
  • 你应该显示settings的确切值。
  • @mscdex settings 是一个字符串,其中包含一些要写入文件的 css 代码
  • 我尝试将模式更改为 0777 但没有运气@jfriend00

标签: node.js electron readonly fs


【解决方案1】:

嘿嘿终于找到问题根源了

问题在于我如何启动电子应用程序。 `

我使用sudo electron . 启动我的应用程序,因为它需要root 访问权限才能执行某些系统任务。因此sudoroot 创建的文件对其他用户只读。要解决我使用chmod() 的问题创建文件后更改文件的权限。

这是我的解决方案:

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

【讨论】:

  • 不需要额外的fs.chmod 调用,因为fs.writeFile 有一个可选的options 参数(see the docs here):fs.writeFile(fileName, settings, { mode: 0666 }, next)
  • @LeonidBeschastny 我试过了,但由于某种原因它不起作用
  • 根据node.js docs,fs.writeFile默认为新创建的文件设置0666模式,这让整个情况变得更加陌生。
  • 当节点以root身份运行时,默认模式可能会改变
  • 刚刚弄清楚为什么 mode 在您的情况下不起作用。它是由 linux umask 引起的。看看similar issue on githubdetailed umask explanation on Ask Ubuntuchmod 有效,因为它不受 umask 的影响。
猜你喜欢
  • 2020-01-04
  • 2020-03-03
  • 2015-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多