← Runnable Projects

阅读中文版本

Chmod Permission Calculator CLI

A Node CLI that converts between octal and symbolic Unix file modes, showing rwx bits and the numeric value in both directions.

beginnerjavascriptunverified

Project

node-chmod-calculator

Entry point: chmod.mjs

Install

node --version

Run

node chmod.mjs 755

Test

node --test chmod.test.mjs

Expected output

Prints the symbolic and octal forms, for example rwxr-xr-x 755 plus the setuid/setgid/sticky bits when present.

Dependencies

  • node >=20

What it does

Converts a three- or four-digit octal mode to a symbolic string, or parses a symbolic string back to octal. Each of the nine permission bits is derived from a small lookup, and special bits are reported separately.

const BIT = ['---', '--x', '-w-', '-wx', 'r--', 'r-x', 'rw-', 'rwx'];

export function octalToSymbolic(mode) {
  const s = String(mode);
  if (!/^[0-7]{3,4}$/.test(s)) throw new SyntaxError('expected 3 or 4 octal digits');
  const digits = s.length === 3 ? '0' + s : s;
  const special = Number(digits[0]);
  const body = digits.slice(1).split('').map((d) => BIT[Number(d)]).join('');
  const flags = [special & 4 ? 'setuid' : null, special & 2 ? 'setgid' : null, special & 1 ? 'sticky' : null].filter(Boolean);
  return body + (flags.length ? ' +' + flags.join(',') : '');
}

const input = process.argv[2];
if (!input) { console.error('usage: chmod <octal-mode>'); process.exit(1); }
console.log(octalToSymbolic(input) + ' (' + input + ')');

Run and verify

node chmod.mjs 755

Run the test command to check the implementation: node --test chmod.test.mjs.

Expected Output

The octal mode 755 expands to user rwx, group r-x, other r-x:

rwxr-xr-x (755)

Limitations

Shows the permission bits only; it does not account for umask, ACLs, or whether the process owner can actually change the mode on a given file.