Industrial
Industrial2y ago

File Permissions on Deno.FileInfo

Hello. As a programming exercise I'm trying to convert a Decimal number into Octal and that Octal representation into a Unix File Permission representation (drwx-). * I have a directory with the number 16877 -> 40755 * I have a file with the number 33188 -> 100644 Questions: * Why does the first Octal number have 5 digits and the second one 6? * I understand the meaning of the last 3 digits, but I don't understand the meaning of the 40 and the 100. Should I interpret the number from right to left? According to ChatGPT: The leftmost digit represents the file type. It can have various values depending on the file type, such as: 0: Regular file 1: FIFO (named pipe) 2: Directory 3: Symbolic link 4: Socket 5: Block device 6: Character device If that's true why is my directory giving me a mode of 4 i.e. Socket and not 2 (Directory)?
3 Replies
javi
javi2y ago
You need to get the permission bits from the st_mode field, by &'ing it with 0o777 Try this snippet:
const getPerms = async (path: string) => {
try {
const fileInfo = await Deno.stat(path);

const permissions = fileInfo.mode! & 0o777;
const owner = {
read: !!(permissions & 0o400),
write: !!(permissions & 0o200),
execute: !!(permissions & 0o100),
};

const group = {
read: !!(permissions & 0o040),
write: !!(permissions & 0o020),
execute: !!(permissions & 0o010),
};

const others = {
read: !!(permissions & 0o004),
write: !!(permissions & 0o002),
execute: !!(permissions & 0o001),
};

return { owner, group, others };
} catch (error) {
console.error("Failed to retrieve file permissions:", error);
return null;
}
};
const getPerms = async (path: string) => {
try {
const fileInfo = await Deno.stat(path);

const permissions = fileInfo.mode! & 0o777;
const owner = {
read: !!(permissions & 0o400),
write: !!(permissions & 0o200),
execute: !!(permissions & 0o100),
};

const group = {
read: !!(permissions & 0o040),
write: !!(permissions & 0o020),
execute: !!(permissions & 0o010),
};

const others = {
read: !!(permissions & 0o004),
write: !!(permissions & 0o002),
execute: !!(permissions & 0o001),
};

return { owner, group, others };
} catch (error) {
console.error("Failed to retrieve file permissions:", error);
return null;
}
};
In order to learn more about the (l)stat function, I recommend you to read the man pages by doing man 2 stat or going to this URL: https://man7.org/linux/man-pages/man2/lstat.2.html (Its C but its the underlying implementation)
Industrial
IndustrialOP2y ago
@jaboolo thanks!
javi
javi2y ago
you're welcome! <:cookie_deno:1002977285734932480>