UNPKG

file-age

Version:

Get file age/timestamp information with human-readable formatting

345 lines (254 loc) • 8.83 kB
# file-age Get file age and timestamp information with human-readable formatting. Simple, fast, and lightweight utility for Node.js applications. ## Features - šŸ•’ **Multiple timestamp types**: modified, created, accessed - šŸ‘ļø **Human-readable output**: "2 hours ago", "3 days ago" - ⚔ **Sync & async support**: Choose what fits your needs - šŸ“ **Batch operations**: Process multiple files at once - šŸ” **File searching**: Find files by age criteria - šŸ“Š **File comparison**: Compare ages between files - šŸŽÆ **TypeScript support**: Full type definitions included - šŸ”§ **Zero dependencies**: Lightweight and fast ## Installation ```bash npm install file-age ``` ## Quick Start ```javascript const fileAge = require('file-age'); // Get timestamp (milliseconds since epoch) const age = await fileAge('package.json'); console.log(age); // 1640995200000 // Get human-readable format const humanAge = await fileAge('package.json', { human: true }); console.log(humanAge); // "2 hours ago" // Get creation time instead of modification time const created = await fileAge('package.json', { type: 'created', human: true }); console.log(created); // "1 day ago" ``` ## API Reference ### fileAge(filePath, options?) **Parameters:** - `filePath` (string): Path to the file - `options` (object, optional): - `human` (boolean): Return human-readable format (default: false) - `type` (string): Timestamp type - 'modified' (default), 'created', 'accessed' - `format` (string): For human format - 'relative' (default), 'absolute' - `precise` (boolean): Include milliseconds (default: false) **Returns:** Promise<number | string> ```javascript // Basic usage await fileAge('file.txt'); // 1640995200000 // Human readable await fileAge('file.txt', { human: true }); // "2 hours ago" // Creation time await fileAge('file.txt', { type: 'created' }); // 1640991600000 // Absolute format await fileAge('file.txt', { human: true, format: 'absolute' }); // "1/1/2022, 12:00:00 PM" // With milliseconds await fileAge('file.txt', { precise: true }); // 1640995200123 ``` ### fileAgeSync(filePath, options?) Synchronous version of `fileAge()`. Same parameters and return type (without Promise). ```javascript const { fileAgeSync } = require('file-age'); const age = fileAgeSync('package.json', { human: true }); console.log(age); // "3 minutes ago" ``` ### fileAgeMultiple(filePaths, options?) Process multiple files at once. **Parameters:** - `filePaths` (string[]): Array of file paths - `options` (object): Same options as `fileAge()` **Returns:** Promise<object> - Object with file paths as keys ```javascript const { fileAgeMultiple } = require('file-age'); const ages = await fileAgeMultiple(['file1.txt', 'file2.txt'], { human: true }); console.log(ages); // { // 'file1.txt': '2 hours ago', // 'file2.txt': '1 day ago' // } ``` ### compareFileAge(file1, file2, options?) Compare ages of two files. ```javascript const { compareFileAge } = require('file-age'); const comparison = await compareFileAge('old-file.txt', 'new-file.txt'); console.log(comparison); // { // file1: { path: 'old-file.txt', timestamp: 1640995200000 }, // file2: { path: 'new-file.txt', timestamp: 1640998800000 }, // newer: 'new-file.txt', // older: 'old-file.txt', // difference: 3600000, // differenceHuman: '1 hour' // } ``` ### findFilesByAge(dirPath, options) Find files in directory based on age criteria. **Parameters:** - `dirPath` (string): Directory path to search - `options` (object): - `olderThan` (number | string): Find files older than this time - `newerThan` (number | string): Find files newer than this time - `recursive` (boolean): Search subdirectories (default: false) Time can be specified as: - Timestamp: `1640995200000` - Duration string: `"2 hours"`, `"1 day"`, `"30 minutes"` - Date string: `"2022-01-01"` ```javascript const { findFilesByAge } = require('file-age'); // Find files older than 1 week const oldFiles = await findFilesByAge('./logs', { olderThan: '1 week', recursive: true }); // Find recently created files (last 2 hours) const recentFiles = await findFilesByAge('./temp', { newerThan: '2 hours' }); ``` ### formatDuration(ms, future?) Format duration in milliseconds as human-readable string. ```javascript const { formatDuration } = require('file-age'); formatDuration(3600000); // "1 hour ago" formatDuration(3600000, true); // "in 1 hour" formatDuration(90000); // "1 minute ago" ``` ## Usage Examples ### Basic File Information ```javascript const fileAge = require('file-age'); async function getFileInfo(filePath) { const modified = await fileAge(filePath, { human: true }); const created = await fileAge(filePath, { type: 'created', human: true }); const accessed = await fileAge(filePath, { type: 'accessed', human: true }); console.log(`File: ${filePath}`); console.log(`Modified: ${modified}`); console.log(`Created: ${created}`); console.log(`Accessed: ${accessed}`); } getFileInfo('important-document.pdf'); ``` ### Cleanup Old Files ```javascript const { findFilesByAge } = require('file-age'); const fs = require('fs').promises; async function cleanupOldFiles(directory, maxAge = '30 days') { try { const oldFiles = await findFilesByAge(directory, { olderThan: maxAge, recursive: true }); console.log(`Found ${oldFiles.length} old files`); for (const file of oldFiles) { await fs.unlink(file); console.log(`Deleted: ${file}`); } } catch (error) { console.error('Cleanup failed:', error.message); } } cleanupOldFiles('./temp', '7 days'); ``` ### Build Cache Validation ```javascript const { compareFileAge } = require('file-age'); async function needsRebuild(sourceFile, outputFile) { try { const comparison = await compareFileAge(sourceFile, outputFile); // Rebuild if source is newer than output if (comparison.newer === sourceFile) { console.log(`${sourceFile} is newer, rebuilding...`); return true; } console.log(`${outputFile} is up to date`); return false; } catch (error) { // If output doesn't exist, we need to build console.log('Output file missing, building...'); return true; } } needsRebuild('src/main.js', 'dist/main.js'); ``` ### File Monitoring Dashboard ```javascript const { fileAgeMultiple } = require('file-age'); async function createDashboard(filesToMonitor) { const ages = await fileAgeMultiple(filesToMonitor, { human: true }); console.log('\nšŸ“Š File Monitor Dashboard'); console.log('========================'); Object.entries(ages).forEach(([file, age]) => { if (age.error) { console.log(`āŒ ${file}: ${age.error}`); } else { console.log(`šŸ“„ ${file}: ${age}`); } }); } const importantFiles = [ 'package.json', 'README.md', 'src/index.js', 'config/database.json' ]; createDashboard(importantFiles); ``` ### Log Rotation ```javascript const { findFilesByAge, fileAge } = require('file-age'); const path = require('path'); async function rotateLogFiles(logDir, maxSize = '100MB', maxAge = '7 days') { // Find old log files const oldLogs = await findFilesByAge(logDir, { olderThan: maxAge }); console.log(`Found ${oldLogs.length} old log files to rotate`); for (const logFile of oldLogs) { const age = await fileAge(logFile, { human: true }); const newName = `${logFile}.${Date.now()}.archived`; console.log(`Archiving ${path.basename(logFile)} (${age})`); // Move or compress the file } } ``` ## Error Handling ```javascript const fileAge = require('file-age'); try { const age = await fileAge('nonexistent-file.txt'); } catch (error) { console.error(error.message); // Possible errors: // - "File not found: nonexistent-file.txt" // - "Permission denied: protected-file.txt" // - "Unable to read file stats: ..." } ``` ## TypeScript Usage ```typescript import fileAge, { FileAgeOptions, compareFileAge } from 'file-age'; const options: FileAgeOptions = { human: true, type: 'modified', format: 'relative' }; const age: string = await fileAge('file.txt', options) as string; ``` ## Platform Support - āœ… **Windows**: Full support for all timestamp types - āœ… **macOS**: Full support for all timestamp types - āœ… **Linux**: Full support for all timestamp types - āš ļø **Note**: Creation time (`birthtime`) may not be available on some older filesystems ## Performance - **Fast**: Uses native `fs.stat()` for optimal performance - **Memory efficient**: Minimal memory footprint - **Batch operations**: Efficiently process multiple files with `fileAgeMultiple()` ## License MIT License. See LICENSE file for details. ## Contributing Pull requests welcome! Please ensure tests pass: ```bash npm test ```