@coffeeandfun/remove-pii

中文文档
3.0.1发布于 2026/04/20MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 4.4万

A Node.js module to remove personally identifiable information (PII) from text.

原始使用文档
文档目录33 节
  1. 🎯 Why use this?
  2. 📦 Installation
  3. 🏃‍♂️ Quick start
  4. 🛡️ PII types detected out of the box
  5. 📦 What you get back
  6. 📚 API reference
  7. removePII(text, options?)
  8. removePIIDetailed(text, options?)
  9. detectPII(text, options?)
  10. analyzePII(text, options?)
  11. validatePIICompliance(text, options?)
  12. processBatch(texts, options?)
  13. getAvailableTypes()
  14. createCustomPattern(type, pattern, replacement, description)
  15. 🎨 Customization
  16. Basic configuration
  17. Privacy levels
  18. 🧩 Custom patterns
  19. 🔧 Advanced features
  20. 📚 Batch processing
  21. ⚖️ Risk assessment
  22. 📖 Inspect available types
  23. 🎭 Real-world examples
  24. 🧽 Log sanitization
  25. 🌐 Express middleware
  26. 🔄 API response scrubbing
  27. 🧼 Data-cleaning pipeline
  28. 🧪 Testing
  29. 🤝 Contributing
  30. Dev setup
  31. 📄 License
  32. 🙏 Credits
  33. 📞 Support

🔒 @coffeeandfun/remove-pii

Protect privacy by removing personally identifiable information (PII) from text!

A Node.js library that automatically detects and removes sensitive information from any string — emails, phone numbers, SSNs, credit cards, addresses, and more. Originally built for Helperbird and now used anywhere privacy matters.

Created with ❤️ by Robert James Gabriel at Coffee & Fun LLC.


🎯 Why use this?

For privacy protection

  • ✅ Automatically removes sensitive information
  • ✅ Prevents accidental data leaks in logs, analytics, and LLM prompts
  • ✅ Helps with GDPR, HIPAA, and general privacy compliance
  • ✅ Fully customizable per use case

For developers

  • ✅ Easy integration — one import, one function call
  • ✅ Zero runtime dependencies
  • ✅ Pure ESM with TypeScript declarations
  • ✅ Detailed analysis and reporting when you need it

📦 Installation

npm install @coffeeandfun/remove-pii

Requires Node.js 16 or newer. The package is pure ESM and ships with TypeScript types out of the box.


🏃‍♂️ Quick start

import { removePII } from '@coffeeandfun/remove-pii';

const text = "John's email is [email protected] and his phone is 123-456-7890.";
const cleaned = removePII(text);

console.log(cleaned);
// "John's email is [email removed] and his phone is [phone removed]."

That's it. Three lines.


🛡️ PII types detected out of the box

TypeExample
📧Email addresses[email protected]
📞Phone numbers123-456-7890, (555) 123-4567
🆔Social Security123-45-6789
💳Credit cards1234 5678 9012 3456
🏠Street addresses123 Main Street
📋Passport numbersAB1234567
🚗Driver's licensesD123456789
🌐IP addresses192.168.1.1
📮ZIP codes12345-6789
🏦Bank accounts1234567890123456
🔗URLshttps://example.com
📅Dates of birth01/15/1990

💡 URLs are detected but not removed by default — pass { url: { remove: true } } if you want them gone too.


📦 What you get back

Every function takes a text string and an optional options object. The shape of the return value depends on which function you call:

// Simple replacement
removePII(text)                   // → string

// Cleaned text + metadata
removePIIDetailed(text)           // → { cleanedText, removedItems, originalLength, cleanedLength, reductionPercentage }

// Locate without changing
detectPII(text)                   // → { text, detectedItems, hasPII, totalMatches, types }

// Full analysis + risk scoring
analyzePII(text)                  // → { original, cleaned, pii, risk }

// Compliance check
validatePIICompliance(text)       // → { isCompliant, violations, violationCount, riskLevel, riskScore, recommendations }

// Array of strings
processBatch(texts)               // → BatchResult[]

Here's what a removePIIDetailed result actually looks like:

{
  cleanedText: 'Email: [email removed]',
  removedItems: [
    {
      type: 'email',
      count: 1,
      items: ['[email protected]'],
      description: 'Email addresses'
    }
  ],
  originalLength: 23,
  cleanedLength: 20,
  reductionPercentage: 13
}

📚 API reference

removePII(text, options?)

The main function — returns the cleaned string.

const cleaned = removePII("Email: [email protected], Phone: 123-456-7890");
// "Email: [email removed], Phone: [phone removed]"

removePIIDetailed(text, options?)

Like removePII but also tells you what was removed.

const result = removePIIDetailed("Email: [email protected]");
// {
//   cleanedText: "Email: [email removed]",
//   removedItems: [{ type: 'email', count: 1, items: ['[email protected]'] }],
//   originalLength: 23,
//   cleanedLength: 20,
//   reductionPercentage: 13
// }

detectPII(text, options?)

Find PII without changing the text. Each detected item includes positions (start / end / value) so you can highlight matches in a UI.

const analysis = detectPII("Email: [email protected], Phone: 123-456-7890");
// {
//   text: "Email: [email protected], Phone: 123-456-7890",
//   hasPII: true,
//   totalMatches: 2,
//   types: ['email', 'phone'],
//   detectedItems: [...]
// }

analyzePII(text, options?)

The full picture — detection + removal + risk scoring all at once. Great for dashboards.

const analysis = analyzePII("Email: [email protected], SSN: 123-45-6789");
// {
//   original: { text: "...", length: 45, wordCount: 6 },
//   cleaned:  { text: "...", length: 35, wordCount: 6 },
//   pii:      { detected: [...], totalCount: 2, types: ['email', 'ssn'] },
//   risk:     { level: 'medium', score: 13 }
// }

validatePIICompliance(text, options?)

Yes/no compliance check with human-readable recommendations.

const compliance = validatePIICompliance("Email: [email protected]");
// {
//   isCompliant: false,
//   violations: [{ type: 'email', count: 1 }],
//   riskLevel: 'low',
//   recommendations: ['📧 Email detected - Consider using hashed or masked emails']
// }

processBatch(texts, options?)

Runs removePIIDetailed over an array. One bad input won't abort the batch — errors come back as { success: false, error }.

getAvailableTypes()

Lists every built-in PII type with its description and default replacement.

createCustomPattern(type, pattern, replacement, description)

Helper for building a custom-pattern options entry (see Custom patterns below).


🎨 Customization

Basic configuration

Pass an options object to enable/disable types and customize replacements. Anything you don't mention keeps its default.

const options = {
  email: { remove: true, replacement: "[EMAIL HIDDEN]" },
  phone: { remove: false },
  ssn:   { remove: true, replacement: "[SSN REDACTED]" }
};

const cleaned = removePII(text, options);

Privacy levels

🔒 High privacy — lock it all down

const highPrivacy = {
  email:          { remove: true },
  phone:          { remove: true },
  ssn:            { remove: true },
  creditCard:     { remove: true },
  address:        { remove: true },
  passport:       { remove: true },
  driversLicense: { remove: true },
  ipAddress:      { remove: true },
  zipCode:        { remove: true },
  bankAccount:    { remove: true },
  url:            { remove: true },
  dateOfBirth:    { remove: true }
};

🛡️ Moderate privacy — financials only

const moderatePrivacy = {
  ssn:         { remove: true },
  creditCard:  { remove: true },
  bankAccount: { remove: true },
  address:     { remove: true },
  email:       { remove: false },
  phone:       { remove: false }
};

🎨 Custom replacements

const customReplacements = {
  email:   { replacement: "📧 [CONTACT INFO]" },
  phone:   { replacement: "📞 [PHONE NUMBER]" },
  address: { replacement: "🏠 [LOCATION]" }
};

🧩 Custom patterns

Need to redact something the library doesn't know about? Drop in your own regex:

import { removePII, createCustomPattern } from '@coffeeandfun/remove-pii';

const options = createCustomPattern(
  'employeeId',
  /\bEMP-\d{6}\b/g,
  '[employee id removed]',
  'Internal employee IDs'
);

removePII('Ticket raised by EMP-123456', options);
// 'Ticket raised by [employee id removed]'

🔧 Advanced features

📚 Batch processing

import { processBatch } from '@coffeeandfun/remove-pii';

const texts = [
  "Email: [email protected]",
  "Phone: 123-456-7890",
  "Regular text"
];

const results = processBatch(texts);
// [{ index: 0, success: true, cleanedText: ..., removedItems: [...] }, ...]

⚖️ Risk assessment

const compliance = validatePIICompliance(text);

console.log(`Risk Level: ${compliance.riskLevel}`);      // 'low' | 'medium' | 'high' | 'critical'
console.log(`Risk Score: ${compliance.riskScore}`);      // weighted numeric score
console.log(`Recommendations:`, compliance.recommendations);

📖 Inspect available types

import { getAvailableTypes } from '@coffeeandfun/remove-pii';

getAvailableTypes().forEach(t => {
  console.log(`${t.type}: ${t.description}`);
});

🎭 Real-world examples

🧽 Log sanitization

import { removePIIDetailed } from '@coffeeandfun/remove-pii';

export function sanitize(entry) {
  const { cleanedText, removedItems } = removePIIDetailed(entry);
  if (removedItems.length > 0) {
    console.debug(`🔒 Sanitized ${removedItems.length} PII item(s)`);
  }
  return cleanedText;
}

🌐 Express middleware

import express from 'express';
import { removePII } from '@coffeeandfun/remove-pii';

const app = express();
app.use(express.json());

app.post('/logs', (req, res) => {
  console.log(removePII(req.body.message));
  res.sendStatus(204);
});

🔄 API response scrubbing

import { analyzePII } from '@coffeeandfun/remove-pii';

export function scrubResponse(body) {
  const result = analyzePII(JSON.stringify(body));
  return result.pii.totalCount > 0
    ? JSON.parse(result.cleaned.text)
    : body;
}

🧼 Data-cleaning pipeline

import { removePII, validatePIICompliance } from '@coffeeandfun/remove-pii';

function cleanUserData(input) {
  const compliance = validatePIICompliance(input);
  if (!compliance.isCompliant) {
    console.warn(`⚠️ PII detected: ${compliance.violationCount} violations`);
    return removePII(input);
  }
  return input;
}

🧪 Testing

npm test

The suite covers:

  • ✅ Every built-in PII type and pattern
  • ✅ Edge cases and error handling
  • ✅ Performance and consistency
  • ✅ Batch processing
  • ✅ Custom configurations

🤝 Contributing

We welcome contributions!

  1. 🐛 Report issues — found a bug or a missing PII type?
  2. 💡 Suggest features — ideas for better privacy protection?
  3. 🔧 Submit PRs — code improvements welcome!

Dev setup

git clone https://github.com/coffee-and-fun/remove-pii
cd remove-pii
npm install
npm test

📄 License

MIT — feel free to use this in your projects.


🙏 Credits

Created with ❤️ by:

  • Robert James Gabriel — Lead Developer

Originally developed for:

  • Helperbird — an accessibility extension making the web more inclusive for everyone

📞 Support

Need help protecting privacy in your applications?

Stay privacy-focused! 🔒

版本与发布记录

@coffeeandfun/remove-pii 共发布 4 个版本,首次发布于 2023/11/23;过去 12 个月发布了 1 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.1latest2026/04/206 个月前
2.0.02025/07/161.3 年前
1.0.52023/11/232 年前
1.0.02023/11/232 年前

关于 @coffeeandfun/remove-pii 的常见问题

@coffeeandfun/remove-pii 是什么?

A Node.js module to remove personally identifiable information (PII) from text.

如何安装 @coffeeandfun/remove-pii?

在项目目录运行 npm install @coffeeandfun/remove-pii,或使用 pnpm add / yarn add / bun add。

@coffeeandfun/remove-pii 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@coffeeandfun/remove-pii 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@coffeeandfun/remove-pii 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@coffeeandfun/remove-pii 可以商用吗?

@coffeeandfun/remove-pii 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@coffeeandfun/remove-pii 的下载量有多少?

根据 npm 官方下载统计,@coffeeandfun/remove-pii 在 2026/10/10 – 2026/11/08 这 30 天内被下载 44,146 次,日均约 1,472 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@coffeeandfun/remove-pii 还在维护吗?

最新版本 3.0.1 发布于 2026/04/20(6 个月前);至今共发布 4 个版本,其中过去 12 个月发布了 1 个;首次发布于 2023/11/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。