Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js fs.writeFile创建只读文件_Node.js_Electron_Readonly_Fs - Fatal编程技术网

Node.js fs.writeFile创建只读文件

Node.js fs.writeFile创建只读文件,node.js,electron,readonly,fs,Node.js,Electron,Readonly,Fs,我正在编写一个电子应用程序,有时我需要将一些文本保存到文件中 我使用对话框模块让用户选择保存文件的位置,并热命名文件。 以下是处理文件创建的代码部分: var exportSettings = (event, settings) => { //settings is a css string console.log(settings) dialog.showSaveDialog({ title: 'Export se

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

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

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);
                });
            }
        });
    }
用户选择目录和文件名后,将创建该文件。但是,该文件被创建为只读,我希望它被创建为每个人都可以编辑。知道为什么会发生这种情况吗?

他们终于找到了问题的根本原因 问题在于我是如何启动我的电子应用程序的`

我使用
sudo electron.
启动我的应用程序,因为它需要root访问权限才能执行某些系统任务。因此,由
sudo
root
创建的文件只能对其他用户读取。为了修复此问题,我使用
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.writeFile()
函数接受一些影响文件的标志。你探索过这个选择吗?这里记录了许多标志:您应该显示
settings
@mscdex
settings
的确切值是一个字符串,其中包含一些要写入文件的css代码。我试图将模式更改为0777,但没有运气@jfriend00,不需要额外的
fs.chmod
调用,因为
fs.writeFile
具有可选的
options
argument():
fs.writeFile(文件名,设置,{mode:0666},next)
@LeonidBeschastny我试过了,但由于某些原因无效根据node.js文档,
fs.writeFile
默认设置新创建文件的
0666
模式,这使得整个情况变得更加奇怪。当节点以root身份运行时,默认模式可能会发生变化。我刚刚了解了
模式在您的情况下不起作用的原因。这是由linux
umask
引起的。看一看和
chmod
之所以有效,是因为它不受
umask
的影响。