如何在 Node.js 中使用 chmod
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8756639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use chmod with Node.js
提问by pvorb
How do I use chmod with Node.js?
如何在 Node.js 中使用 chmod?
There is a method in the package fs, which should do this, but I don't know what it takes as the second argument.
包中有一个方法fs,它应该这样做,但我不知道它作为第二个参数需要什么。
fs.chmod(path, mode, [callback])
Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback.
fs.chmodSync(path, mode)
Synchronous chmod(2).
fs.chmod(路径,模式,[回调])
异步 chmod(2)。除了可能的异常之外,没有为完成回调提供任何参数。
fs.chmodSync(路径,模式)
同步 chmod(2)。
(from the Node.js documentation)
(来自Node.js 文档)
If I do something like
如果我做类似的事情
fs.chmodSync('test', 0755);
nothing happens (the file isn't changed to that mode).
没有任何反应(文件不会更改为该模式)。
fs.chmodSync('test', '+x');
doesn't work either.
也不起作用。
I'm working on a Windows machine btw.
顺便说一句,我正在 Windows 机器上工作。
回答by qiao
According to its sourcecode /lib/fs.json line 508:
根据/lib/fs.js第 508 行的源代码:
fs.chmodSync = function(path, mode) {
return binding.chmod(pathModule._makeLong(path), modeNum(mode));
};
and line 203:
和第 203 行:
function modeNum(m, def) {
switch (typeof m) {
case 'number': return m;
case 'string': return parseInt(m, 8);
default:
if (def) {
return modeNum(def);
} else {
return undefined;
}
}
}
it takes either an octal number or a string.
它需要一个八进制数或一个字符串。
e.g.
例如
fs.chmodSync('test', 0755);
fs.chmodSync('test', '755');
It doesn't work in your case because the file modes only exist on *nix machines.
它在您的情况下不起作用,因为文件模式仅存在于 *nix 机器上。
回答by nesty
The correct way to specify Octal is as follows:
指定 Octal 的正确方法如下:
fs.chmodSync('test', 0o755);
Refer to the file modes here
请参阅此处的文件模式

