Q1. How do you get file statistics in Node.js?
Use fs.stat(), fs.lstat() (for symbolic links), or fs.fstat() (with file descriptor).
Example:
stats is a fs.Stats object containing file metadata like size, permissions, timestamps, and type information.
Example:
fs.stat('file.txt', (err, stats) => { if (err) throw err; console.log(stats); });stats is a fs.Stats object containing file metadata like size, permissions, timestamps, and type information.
Q2. What information does the Stats object provide?
The Stats object provides: .size (file size in bytes), .atime (last access time), .mtime (last modification time), .ctime (creation/change time), .birthtime (birth time), .mode (permissions), .uid/.gid (owner/group IDs). Also methods like .isFile(), .isDirectory(), .isSymbolicLink(), .isSocket(), etc.
Q3. How do you check if a path is a file or directory?
After getting stats, use .isFile() and .isDirectory().
Example:
For symbolic links, use fs.lstat() first and then .isSymbolicLink().
Example:
fs.stat('path', (err, stats) => { if (stats.isFile()) console.log('File'); else if (stats.isDirectory()) console.log('Directory'); });For symbolic links, use fs.lstat() first and then .isSymbolicLink().
Q4. How do you get file permissions?
File permissions are in stats.mode. You can extract them using bitmasks.
Example:
For checking specific permissions, use fs.access():
Example:
const mode = stats.mode & 0o777; // gets the permission bits.For checking specific permissions, use fs.access():
fs.access('file', fs.constants.R_OK, (err) => { console.log(err ? 'not readable' : 'readable') });Q5. What's the difference between stat, lstat, and fstat?
fs.stat() follows symbolic links - it returns stats of the target.
fs.lstat() works on the symbolic link itself, not its target.
fs.fstat() takes a file descriptor (from fs.open()) and returns stats for that open file.
Choose based on whether you need info about the link or the target.
fs.lstat() works on the symbolic link itself, not its target.
fs.fstat() takes a file descriptor (from fs.open()) and returns stats for that open file.
Choose based on whether you need info about the link or the target.
