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
@mscdexsettings
的确切值是一个字符串,其中包含一些要写入文件的css代码。我试图将模式更改为0777,但没有运气@jfriend00,不需要额外的fs.chmod
调用,因为fs.writeFile
具有可选的options
argument():fs.writeFile(文件名,设置,{mode:0666},next)
@LeonidBeschastny我试过了,但由于某些原因无效根据node.js文档,fs.writeFile
默认设置新创建文件的0666
模式,这使得整个情况变得更加奇怪。当节点以root身份运行时,默认模式可能会发生变化。我刚刚了解了模式在您的情况下不起作用的原因。这是由linuxumask
引起的。看一看和chmod
之所以有效,是因为它不受umask
的影响。