Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use chmod with Node.js

Tags:

node.js

chmod

fs

How do I use chmod with Node.js?

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.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).

(from the Node.js documentation)

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.

like image 429
pvorb Avatar asked Jan 06 '12 10:01

pvorb


People also ask

How do I change permissions in node JS?

To change the permissions of a file in a Node. js program asynchronously, we can use the chmod function. It takes three arguments. The first argument is the reference to the file, which can be a string path, a Buffer object, a URL object, or a file descriptor, which is an integer that identifies the file.

What does chmod 755 do?

When you perform chmod 755 filename command you allow everyone to read and execute the file, the owner is allowed to write to the file as well. So, there should be no permission to everyone else other than the owner to write to the file, 755 permission is required.


2 Answers

According to its sourcecode /lib/fs.js on line 508:

fs.chmodSync = function(path, mode) {   return binding.chmod(pathModule._makeLong(path), modeNum(mode)); }; 

and line 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.

like image 163
qiao Avatar answered Oct 14 '22 17:10

qiao


The correct way to specify Octal is as follows:

fs.chmodSync('test', 0o755);  

Refer to the file modes here.

like image 44
Rajitha Wijayaratne Avatar answered Oct 14 '22 16:10

Rajitha Wijayaratne