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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@vic-lib/fs-retention

v1.0.0

Published

## 安装

Readme

fs-retention - 文件保留策略管理工具

安装

npm install fs-retention
# 或
yarn add fs-retention

简介

fs-retention 是一个轻量级、无依赖的 Node.js 工具库,用于实现基于分层保留策略的文件管理。特别适合日记应用、备份系统和日志管理场景,提供简单易用的 API 来自动清理过期文件。

核心功能

  • 📅 基于日/周/月的分层保留策略
  • 🗑️ 自动清理过期文件
  • ⚙️ 可配置的保留规则
  • 📊 详细的清理报告
  • 🧪 支持模拟运行(dry-run)模式

快速开始

import RetentionManager from 'fs-retention';

// 创建保留管理器实例
const manager = new RetentionManager({
  path: './backups', // 备份目录
  retention: {
    daily: 7,   // 保留最近7天的每日备份
    weekly: 4,  // 保留最近4周的每周备份
    monthly: 6  // 保留最近6个月的每月备份
  }
});

// 执行清理
const result = await manager.clean();
console.log('清理结果:', result);

预设策略

fs-retention 提供三种预设策略,适合不同需求的日记应用:

1. 精简实用型

const strategy = RetentionManager.strategies.BASIC;
// 等同于 { daily: 7, weekly: 4, monthly: 3 }

2. 均衡覆盖型 (推荐)

const strategy = RetentionManager.strategies.BALANCED;
// 等同于 { daily: 14, weekly: 6, monthly: 12 }

3. 长期珍藏型

const strategy = RetentionManager.strategies.PREMIUM;
// 等同于 { daily: 30, weekly: 12, monthly: 24 }

完整使用示例

import RetentionManager from 'fs-retention';

async function manageDiaryBackups() {
  // 使用预设策略
  const manager = new RetentionManager({
    path: './diary-backups',
    retention: RetentionManager.strategies.BALANCED,
    
    // 可选配置
    filenameParser: (filename) => {
      // 从文件名中提取日期 (例如: diary-20230501.json)
      const match = filename.match(/diary-(\d{8})\.json/);
      return match ? match[1] : null;
    },
    dryRun: false, // 设为 true 可测试而不实际删除
    logger: console // 自定义日志记录器
  });

  // 执行清理
  const result = await manager.clean();
  
  console.log('===== 清理报告 =====');
  console.log(`保留文件: ${result.kept.daily} 天, ${result.kept.weekly} 周, ${result.kept.monthly} 月`);
  console.log(`删除文件: ${result.deletedCount} 个`);
  console.log(`释放空间: ${result.spaceFreed}`);
  
  if (result.deletedCount > 0) {
    console.log('\n删除的文件:');
    result.deletedFiles.forEach(file => console.log(`- ${file}`));
  }
}

manageDiaryBackups().catch(console.error);

API 文档

new RetentionManager(options)

创建保留管理器实例。

参数:

  • options (Object):
    • path (String): 要管理的目录路径
    • retention (Object): 保留策略配置
      • daily (Number): 保留的每日备份数量
      • weekly (Number): 保留的每周备份数量
      • monthly (Number): 保留的每月备份数量
    • filenameParser (Function): 从文件名提取日期的函数 (可选)
    • dryRun (Boolean): 模拟运行模式 (默认: false)
    • logger (Object): 自定义日志记录器 (默认: console)

manager.clean()

执行清理操作,返回 Promise 解析为清理报告对象。

返回:

{
  status: 'completed' | 'failed',
  message: String,
  totalFound: Number,
  kept: {
    daily: Number,
    weekly: Number,
    monthly: Number
  },
  deletedCount: Number,
  spaceFreed: String,
  deletedFiles: String[]
}

RetentionManager.strategies

预设策略常量:

  • BASIC: 精简实用型策略
  • BALANCED: 均衡覆盖型策略
  • PREMIUM: 长期珍藏型策略

文件名解析器

默认情况下,fs-retention 会尝试从文件名中提取 8 位数字日期 (YYYYMMDD)。如果需要自定义解析逻辑:

const manager = new RetentionManager({
  path: './backups',
  retention: { daily: 7, weekly: 4, monthly: 6 },
  filenameParser: (filename) => {
    // 自定义解析逻辑
    // 返回日期字符串 (YYYYMMDD 格式) 或时间戳
    const match = filename.match(/backup-(\d{4}-\d{2}-\d{2})\.zip/);
    if (match) {
      return match[1].replace(/-/g, ''); // 转换为 YYYYMMDD
    }
    return null;
  }
});

最佳实践

  1. 定期执行:在应用启动时或每天固定时间执行清理
  2. 备份后清理:在创建新备份后立即执行清理
  3. 日志记录:记录清理结果以便审计
  4. 测试验证:首次使用时启用 dry-run 模式验证效果
// 在Express应用中使用
import express from 'express';
import RetentionManager from 'fs-retention';

const app = express();

// 每天凌晨2点执行清理
const scheduleCleanup = () => {
  const now = new Date();
  const nextRun = new Date(now);
  nextRun.setDate(nextRun.getDate() + 1);
  nextRun.setHours(2, 0, 0, 0);
  
  const delay = nextRun - now;
  
  setTimeout(async () => {
    const manager = new RetentionManager({
      path: './diary-backups',
      retention: RetentionManager.strategies.BALANCED
    });
    
    const result = await manager.clean();
    console.log('自动清理完成:', result);
    
    scheduleCleanup(); // 安排下一次清理
  }, delay);
};

scheduleCleanup();

app.listen(3000, () => {
  console.log('日记应用已启动');
});

贡献与支持

欢迎提交 issue 或 pull request:

许可证

MIT © 2025 stevobm & DeepSeek