npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

file-age

v1.0.0

Published

Get file age/timestamp information with human-readable formatting

Readme

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

npm install file-age

Quick Start

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>

// 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).

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 with file paths as keys

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.

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"
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.

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

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

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

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

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

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

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

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:

npm test