File Stats & Information
Imagine you're a detective examining a file. You want to know how old it is, how big it is, who owns it, and whether it's a file or a folder. In Node.js, the `fs.stat()` method gives you all this detective information about files and directories.
What are File Stats?
File stats provide detailed information about a file or directory:
- Size – How many bytes
- Creation time – When it was created
- Modification time – When it was last changed
- Access time – When it was last read
- Permissions – Who can read/write/execute
- Type – File, directory, symlink, etc.
Think of `fs.stat()` as the file's ID card – it tells you everything about the file's identity and history.
Getting File Stats (fs.stat)
const fs = require('fs');
fs.stat('sample.txt', (err, stats) => { if (err) { console.error('Error getting stats:', err); return; } console.log(stats);});Stats Object Properties
| Property | Description |
|---|---|
| `stats.size` | File size in bytes |
| `stats.birthtime` | File creation timestamp |
| `stats.mtime` | Last modification timestamp |
| `stats.atime` | Last access timestamp |
| `stats.ctime` | Status change timestamp (permissions, ownership) |
| `stats.mode` | File permissions (as a number) |
| `stats.uid` | User ID of owner |
| `stats.gid` | Group ID of owner |
Checking File Type
Stats provides methods to check what kind of filesystem object you're dealing with.
fs.stat('sample.txt', (err, stats) => { if (err) { console.error(err); return; } console.log('Is file?', stats.isFile()); <!-- true if file --> console.log('Is directory?', stats.isDirectory()); <!-- true if folder --> console.log('Is symbolic link?', stats.isSymbolicLink());});Reading File Sizes
Get file size in a human-readable format.
function formatBytes(bytes, decimals = 2) { if (bytes === 0) return '0 Bytes'; const k = 1024; const dm = decimals < 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];}
fs.stat('large-file.zip', (err, stats) => { if (err) throw err; console.log('File size:', formatBytes(stats.size));});Working with Timestamps
fs.stat('document.pdf', (err, stats) => { if (err) throw err; console.log('Created:', stats.birthtime); console.log('Modified:', stats.mtime); console.log('Accessed:', stats.atime); <!-- Calculate age in days --> const ageMs = Date.now() - stats.birthtime; const ageDays = Math.floor(ageMs / (1000 * 60 * 60 * 24)); console.log('File age:', ageDays, 'days');});File Permissions
The `stats.mode` contains permission information in numeric format.
fs.stat('script.sh', (err, stats) => { if (err) throw err; <!-- Convert mode to octal for readable permissions --> const mode = stats.mode.toString(8); console.log('Permissions (octal):', mode); <!-- Check if file is executable for owner --> const isExecutable = !!(stats.mode & fs.constants.S_IXUSR); console.log('Is executable?', isExecutable);});Using Promises with fs.stat
const fs = require('fs').promises;
async function getFileInfo(filePath) { try { const stats = await fs.stat(filePath); console.log(`File: ${filePath}`); console.log(`Size: ${stats.size} bytes`); console.log(`Created: ${stats.birthtime}`); console.log(`Is directory: ${stats.isDirectory()}`); } catch (err) { console.error(`Error getting stats for ${filePath}:`, err.message); }}
getFileInfo('sample.txt');Practical Example: File Cleanup by Age
Delete files older than 30 days.
const fs = require('fs').promises;const path = require('path');
async function cleanOldFiles(directory, maxAgeDays = 30) { try { const files = await fs.readdir(directory); const now = Date.now(); const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1000; for (const file of files) { const filePath = path.join(directory, file); const stats = await fs.stat(filePath); if (stats.isFile() && (now - stats.mtime) > maxAgeMs) { await fs.unlink(filePath); console.log(`Deleted old file: ${file}`); } } } catch (err) { console.error('Cleanup error:', err); }}
cleanOldFiles('./logs', 7); <!-- Delete log files older than 7 days -->Two Minute Drill
- `fs.stat()` gives you detailed information about files and directories.
- Use `stats.isFile()` and `stats.isDirectory()` to check type.
- Access timestamps: `birthtime` (creation), `mtime` (modification), `atime` (access).
- File size is in bytes – convert to human-readable format as needed.
- Permissions are in `stats.mode` – use bitwise operations to check.
- Always use try/catch with promises or check errors in callbacks.
Need more clarification?
Drop us an email at career@quipoinfotech.com
