Course contentsShow
← JavaScript
Lesson 1529 of 2,72333. JavaScript in Node.jsFree lesson

File Permissions and Ownership with fs.chmod() and fs.chown()

Modifying file permissions and ownership on Unix-like systems.

File Permissions and Ownership with fs.chmod() and fs.chown()

You'll learn how to programmatically modify file permissions and ownership in Node.js on Unix-like systems.

Understanding the Concept

On Unix-like operating systems (Linux, macOS), every file has associated permissions (who can read, write, or execute it) and ownership (which user and group owns it). Node.js provides fs.chmod() and fs.chown() to modify these properties programmatically.

Think of file permissions like house access levels: some people can only look (read), others can rearrange furniture (write), and some can operate the security system (execute). Ownership determines who controls these permissions.

Using fs.chmod()

fs.chmod() changes file permissions using a mode (often represented in octal notation):

import fs from 'fs/promises';

// Make a file readable and writable by owner only
await fs.chmod('myfile.txt', 0o600);

// Make it executable for everyone
await fs.chmod('script.sh', 0o755);

The octal numbers represent permissions: 0o755 means owner has full access (7=read+write+execute), while group and others can read and execute (5=read+execute).

Using fs.chown()

fs.chown() changes file ownership by specifying user ID (uid) and group ID (gid):

// Change ownership (requires appropriate permissions)
await fs.chown('myfile.txt', 1001, 1001);

Note: Changing ownership typically requires elevated privileges (root/sudo) on most systems.

Practical Considerations

These functions are primarily useful on Unix-like systems. On Windows, they have limited or no effect. Always handle potential permission errors with try-catch blocks, as modifying these properties often requires specific system privileges.

Key Takeaway: Use fs.chmod() to modify file permissions and fs.chown() to change ownership on Unix-like systems, enabling programmatic control over file access and security.