57

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.

Joe Flynn
  • 6,908
  • 6
  • 31
  • 44
pvorb
  • 7,157
  • 7
  • 47
  • 74
  • 2
    I think windows permissions are more complicated... you might want to open an issue on github if you can't solve it. – thejh Jan 06 '12 at 19:07
  • 1
    Have to agree with @thejh on this one... Windows file permissions are much more complicated. You may need to execute commands to cmd.exe or similar. – Tracker1 Jan 06 '12 at 19:26

3 Answers3

69

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.

Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
qiao
  • 17,941
  • 6
  • 57
  • 46
  • Sorry, I haven't played with MSYS, and simply don't know how it works. Maybe it's just a kind of simulation(forgive me if I'm wrong). This post may be of help: http://stackoverflow.com/questions/8682672/how-does-chmod-work-for-windows – qiao Jan 06 '12 at 12:19
  • 1
    MSYS seems to ignore file modes. – pvorb Jun 15 '12 at 11:49
22

The correct way to specify Octal is as follows:

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

Refer to the file modes here.

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
0

On Windows, instead of on Octal number or string, you need to use fs.constants or fsPromises.constants. For example, to change a file to open for read only access you would use:

fs.chmodSync(filePath, fs.constants.O_RDONLY)

You can find the values for fs.constants here: Node File System Constants

CascadiaJS
  • 2,320
  • 2
  • 26
  • 46