Back to JavaScript
2026-01-147 min read

File Permissions (JavaScript)

Learn File Permissions (JavaScript) step by step with clear examples and exercises.

Title: Mastering File Permissions in JavaScript - A full guide to Access Control

Why This Matters

In the realm of web development, managing file permissions is essential for maintaining secure and efficient operations of your applications. Understanding how to set and modify file permissions using JavaScript can help you avoid common security vulnerabilities and streamline your workflow when deploying and maintaining projects.

Prerequisites

To follow this tutorial, you should be familiar with:

  • Basic JavaScript concepts (variables, functions, loops)
  • Node.js and the fs module for file system operations
  • Familiarity with Unix-like file permissions and their importance in securing your files

Core Concept

The fs (File System) module in Node.js allows you to read, write, and manage files on your server. To work with file permissions, we'll use the chmod function, which stands for "change mode." This function lets you modify the access permissions of a file or directory.

File Permissions Basics

File permissions in Unix-like systems (including Node.js) are represented by a combination of three sets of permissions:

  1. Owner permissions (u)
  2. Group permissions (g)
  3. Other permissions (o)

Each set consists of read (r), write (w), and execute (x) permissions. When a permission is not explicitly set, it defaults to -.

Owner, Group, and Other Users

In Unix-like systems, files and directories belong to a user and a group. The owner of the file or directory has the highest level of access, followed by members of the file's group, and then all other users on the system.

Permission Symbols

File permissions are represented using symbols: r (read), w (write), x (execute), and - (no permission). For example, a file with read and write permissions for the owner would be represented as rw-.

Setting File Permissions with chmod

The chmod function takes two arguments: the file path and the desired permissions in octal format. The permissions are represented as the sum of three sets (owner, group, other) with each set being the sum of read, write, and execute permissions.

For example, to give the owner full control (read, write, and execute), the group read and execute permission, and no permissions for others:

const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'exampleFile.txt');
const permissions = 0o750; // Owner (4) + Read & Execute (5) for Group (2) + No Permissions (0) for Others (0)

fs.chmod(filePath, permissions, (err) => {
if (err) throw err;
console.log('File permissions updated');
});

Understanding Octal Permissions

The octal format of file permissions is a compact way to represent the three sets of permissions using three digits:

  • The first digit represents the owner's permissions (4 bits)
  • The second digit represents the group's permissions (3 bits)
  • The third digit represents other permissions (3 bits)

For example, in the previous code snippet, 0o750 can be broken down as follows:

  • Owner permissions: 0111 (4 bits) - read (4), write (2), and execute (1)
  • Group permissions: 010 (3 bits) - read (2), and execute (1)
  • Other permissions: 000 (3 bits) - no permissions

Permissions Calculation

To calculate the octal representation of a given set of permissions, you can sum up the values for each permission as follows:

  • Read: 4
  • Write: 2
  • Execute: 1

For example, to represent read and write permissions for the owner only (rw-r--r--), you would calculate 4 + 0 + 0 = 4.

Worked Example

Let's create a simple Node.js script that sets file permissions for multiple files based on different permission configurations.

const fs = require('fs');
const path = require('path');

// Define the directory containing our example files
const dirPath = path.join(__dirname, 'exampleFiles');

// Function to set file permissions for a given file and permissions
function setFilePermissions(filePath, permissions) {
fs.chmod(filePath, permissions, (err) => {
if (err) throw err;
console.log(`${filePath} permissions updated`);
});
}

// Set example file permissions
const files = [
path.join(dirPath, 'exampleFile1.txt'),
path.join(dirPath, 'exampleFile2.txt'),
path.join(dirPath, 'exampleFile3.txt')
];

const ownerPermissions = 0o700; // Owner (4) + Read & Write (6) for Owner (4) + No Permissions (0) for Others (0)
const groupPermissions = 0o640; // Owner (4), Group (2), and Read (4) permissions for Owner (4), Group (2), and Others (0)
const allPermissions = 0o777; // Full permissions for Owner (4), Group (2), and Others (1)

files.forEach((filePath) => {
setFilePermissions(filePath, ownerPermissions);
});

setTimeout(() => {
files.forEach((filePath) => {
setFilePermissions(filePath, groupPermissions);
});
}, 2000); // Wait 2 seconds to demonstrate the effect of changing permissions

setTimeout(() => {
files.forEach((filePath) => {
setFilePermissions(filePath, allPermissions);
});
}, 4000); // Wait another 2 seconds to give time for the group permissions to take effect

Common Mistakes

  1. Using decimal instead of octal format: Remember that file permissions are represented in octal format, not decimal. Use 0o before your permissions to ensure they're interpreted correctly.
  2. Not handling errors: Always check for errors when working with the file system and handle them gracefully using try-catch blocks or error callbacks.
  3. Incorrect permissions: Make sure you understand the octal format and set the correct permissions for each situation.
  4. Forgetting to specify the owner and group: When setting permissions, always ensure that you specify the owner and group if needed, as these may not be the default user and group of your Node.js process.

Common Mistakes (continued)

  1. Not considering file or directory type: File permissions for directories differ from those for files. For example, to allow others to traverse a directory, you need to set execute permission for others (o+x).
  2. Forgetting to update ownership and group: If you're deploying your application on a server, make sure to update the ownership and group of your files to match those of the user running the web server.

Practice Questions

  1. Write a Node.js script to recursively find all files in a given directory and its subdirectories, then set their owner permissions to 0o700.
  2. Given the file path /home/user/exampleFile.txt, what octal permissions would you use to give the user (owner) read-only access, group read-write access, and others no access?
  3. Write a Node.js script that sets different permissions for multiple files based on their extensions:
  • .txt files should have owner permissions of 0o755
  • .json files should have owner permissions of 0o644
  • All other files should have owner permissions of 0o700
  1. Write a Node.js script that sets execute permission for others on all directories in a given directory and its subdirectories, while maintaining existing file permissions.
  2. Given the following file permissions: drwxr-xr-x, what are the owner's read, write, and execute permissions? What about group and other permissions?
  3. What is the octal representation of the following permissions: read only for owner, read, write, and execute for group, and no permissions for others?
  4. Write a Node.js script that sets the same file permissions for all files in a given directory and its subdirectories based on a provided set of permissions (e.g., 0o755).
  5. Given the following file path: /var/www/exampleFile.txt, what octal permissions would you use to give the owner full control, group read-only access, and others no access?
  6. Write a Node.js script that sets different permissions for multiple files based on their ownership:
  • Files owned by user "user1" should have owner permissions of 0o755
  • Files owned by user "user2" should have owner permissions of 0o644
  • All other files should have owner permissions of 0o700

FAQ

  1. Why are file permissions important? File permissions help ensure the security and integrity of your files by controlling who can read, write, or execute them. They prevent unauthorized access and accidental modifications.
  2. What does the octal format represent in file permissions? The octal format represents a combination of three sets of permissions (owner, group, other) with each set being the sum of read, write, and execute permissions.
  3. How do I check the current permissions of a file using Node.js? To check the current permissions of a file in Node.js, you can use the fs.stat function to get the mode property of the file's stats object. Then, convert the mode from binary format to octal format using the following code:
const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'exampleFile.txt');

fs.stat(filePath, (err, stats) => {
if (err) throw err;
const permissions = stats.mode.toString(8);
console.log(`Current permissions: ${permissions}`);
});
  1. How can I change the owner and group of a file using Node.js? To change the owner and group of a file in Node.js, you can use the chown function. Here's an example:
const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'exampleFile.txt');
const newOwner = 'username'; // Replace with the desired username
const newGroup = 'groupname'; // Replace with the desired group name

fs.chown(filePath, newOwner, newGroup, (err) => {
if (err) throw err;
console.log('File ownership updated');
});
File Permissions (JavaScript) | JavaScript | XQA Learn