# @coffeeandfun/remove-pii 中文文档

规范地址：https://npmcn.com/package/%40coffeeandfun/remove-pii/

版本：3\.0\.1
npm 元数据更新时间：2026-04-20T04:12:18.469Z
中文译文更新时间：2026-11-10T09:34:28.789Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40coffeeandfun/remove-pii
原文对照：https://npmcn.com/package/%40coffeeandfun/remove-pii/?lang=original
项目主页：https://github.com/coffee-and-fun/remove-pii#readme
源码仓库：https://github.com/coffee-and-fun/remove-pii

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：33.4 kB，16 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=16
- 运行依赖：0 个
- 首次发布：2023-11-23T03:15:52.844Z
- 最新版本发布：2026-04-20T04:12:18.119Z
- 近 30 天下载量：44146（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：4（近 12 个月 1 个）

## 中文简介

一个从文本中删除个人可识别信息的节点.js模块.

## 安装

```sh
npm install @coffeeandfun/remove-pii
```

也可以使用：`pnpm add @coffeeandfun/remove-pii`、`yarn add @coffeeandfun/remove-pii`、`bun add @coffeeandfun/remove-pii`

## README

# @coffeeandfun/ remove-pii (英语)

**通过从文本中删除个人可识别信息(PII)来保护隐私!**

一个Node.js库可以自动从任何字符串中检测并去除敏感信息——电子邮件,电话号码,SSN,信用卡,地址等等. 原为 [帮助鸟](https://helperbird.com/) {\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}现在在任何地方使用隐私.

由QQ 创建 **罗伯特·詹姆斯·加布里埃尔** 时间 **咖啡和娱乐有限责任公司**。 。 。 .

* * *

## 为什么用这个?

**保护隐私**

-   自动删除敏感信息
-   防止日志、分析和LLM中意外数据泄露
-   \* 帮助处理GDPR、HIPAA和一般隐私问题
-   每个使用案例可完全定制

**对于开发者**

-   QQ 简单集成——一个导入,一个函数调用
-   零运行时间依赖关系
-   纯无害环境管理与类型脚本声明
-   \* 在需要时详细分析和报告

* * *

## \* 安装

```bash
npm install @coffeeandfun/remove-pii
```

要求数 **节点.js 16或更新**。该包件是纯无害环境管理的,并带有类型为外框的船舶.

* * *

## 快速启动

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

const text = "John's email is john@example.com 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]."
```

就是这样。 三行经.

* * *

## 从框中检测到的 PII 类型

|  | 类型 | 示例 |
| :-: | --- | --- |
| 📧 | 电子邮件地址 | `john@example.com` |
| 📞 | 电话号码 | `123-456-7890`, (中文(简体) ), `(555) 123-4567` |
| 🆔 | 社会保障 | `123-45-6789` |
| 💳 | 信用卡 | `1234 5678 9012 3456` |
| 🏠 | 街道地址 | `123 Main Street` |
| 📋 | 护照号码 | `AB1234567` |
| 🚗 | 驾驶执照 | `D123456789` |
| 🌐 | IP 地址 | `192.168.1.1` |
| 📮 | ZIP 代码 | `12345-6789` |
| 🏦 | 银行账户 | `1234567890123456` |
| 🔗 | URL( URL) | `https://example.com` |
| 📅 | 出生日期 | `01/15/1990` |

> 检测到 QQ URL 但 **没有** 默认删除——通过 `{ url: { remove: true } }` 如果你想让他们也消失.

* * *

## 你拿回来的

每个函数都有一个 `text` 字符串和可选 `options` 对象。 返回值的形状取决于您调用的函数 :

```js
// 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[]
```

是这样的 `removePIIDetailed` 结果实际上看起来像:

```js
{
  cleanedText: 'Email: [email removed]',
  removedItems: [
    {
      type: 'email',
      count: 1,
      items: ['john@example.com'],
      description: 'Email addresses'
    }
  ],
  originalLength: 23,
  cleanedLength: 20,
  reductionPercentage: 13
}
```

* * *

## API 参考

### `removePII(text, options?)`

主函数——返回被清理的字符串.

```js
const cleaned = removePII("Email: john@example.com, Phone: 123-456-7890");
// "Email: [email removed], Phone: [phone removed]"
```

### `removePIIDetailed(text, options?)`

喜欢 `removePII` 也告诉你 **什麽** 被删除.

```js
const result = removePIIDetailed("Email: john@example.com");
// {
//   cleanedText: "Email: [email removed]",
//   removedItems: [{ type: 'email', count: 1, items: ['john@example.com'] }],
//   originalLength: 23,
//   cleanedLength: 20,
//   reductionPercentage: 13
// }
```

### `detectPII(text, options?)`

寻找 PII **无** 更改文本。 每个检测到的物品包括: `positions` (单位:千美元)`start` 编号 : `end` 编号 : `value`) 这样您可以在 UI 中突出显示匹配 .

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

### `analyzePII(text, options?)`

全局——检测+去除+风险分数全部一次. 对仪表板来说很好.

```js
const analysis = analyzePII("Email: john@example.com, 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?)`

是/没有检查是否遵守人可读的建议.

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

### `processBatch(texts, options?)`

运行 `removePIIDetailed` 在一个阵列上。 一个错误输入不会中止批次——错误会作为 `{ success: false, error }`。 。 。 .

### `getAvailableTypes()`

列出每个内置的 PII 类型及其描述和默认替换.

### `createCustomPattern(type, pattern, replacement, description)`

用于构建自定义模式选项条目的助手(参见 [自定义图案](https://npmcn.com/package/%40coffeeandfun/remove-pii/#readme--custom-patterns) 页:1.

* * *

## 🎨自定义

### 基本配置

通过一个 `options` 对象,用于启用/失效类型并自定义替换。 凡你没有提到的,都保持它的默认.

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

const cleaned = removePII(text, options);
```

### 隐私水平

#### 高隐私——全锁上

```js
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 }
};
```

#### \* 适度隐私——仅限财务

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

#### 自定义替换

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

### QQ 自定义模式

需要编辑图书馆不知道的东西吗? 掉入自己的目录 :

```js
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]'
```

* * *

## 高级特性

### 批量处理

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

const texts = [
  "Email: john@example.com",
  "Phone: 123-456-7890",
  "Regular text"
];

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

### 风险评估

```js
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);
```

### 📖 检查可用类型

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

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

* * *

## 现实世界实例

### 逻辑消毒

```js
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;
}
```

### QQ 快速中间软件

```js
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 反应清洗

```js
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;
}
```

### 数据清理管道

```js
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;
}
```

* * *

## 测试

```bash
npm test
```

套房覆盖:

-   \* 每一个内置PII类型和模式
-   \* 边缘案件和错误处理
-   \* 业绩和一致性
-   批量处理
-   QQ 自定义配置

* * *

## 捐款

我们欢迎捐款!

1.  🐛 **报告问题** - 找到一个错误或缺失的 PII 类型?
2.  💡 **建议的特性** - 如何更好地保护隐私?
3.  🔧 **提交 PR** - 代码改进欢迎!

### 设置

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

* * *

## 许可证

[麻省理工学院](https://npmcn.com/package/%40coffeeandfun/remove-pii/LICENSE) ——在你的项目中随意使用这个.

* * *

## • 信贷

**由 QQ 创建 :**

-   **罗伯特·詹姆斯·加布里埃尔** ——主要开发者

**最初为:**

-   **[帮助鸟](https://helperbird.com/)** ——无障碍扩展,使网络更加包容所有人

* * *

## ++ 辅助

申请时需要保护隐私吗?

-   🐛 **错误报告 :** [GitHub 问题](https://github.com/coffee-and-fun/remove-pii/issues)
-   💡 **特性请求 :** [GitHub 讨论](https://github.com/coffee-and-fun/remove-pii/discussions)
-   🔐 **安全问题:** 见 [警卫](https://npmcn.com/package/%40coffeeandfun/remove-pii/SECURITY.md)

**专注隐私**

## 常见问题

### @coffeeandfun/remove-pii 是什么？

一个从文本中删除个人可识别信息的节点\.js模块\.

### 如何安装 @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 和提交记录判断。

