randexp vs faker vs chance vs casual
JavaScript 假数据生成库选型指南
randexpfakerchancecasual类似的npm包:

JavaScript 假数据生成库选型指南

casualchancefaker(特指 @faker-js/faker)和 randexp 都是用于生成假数据的 JavaScript 库,但目标和能力差异显著。casualchancefaker 提供姓名、地址、邮箱等常见数据类型的模拟,适用于测试、原型开发和本地调试;而 randexp 专注于根据正则表达式生成匹配的随机字符串,常用于生成特定格式的标识符。值得注意的是,原始 faker 包已不再维护,当前推荐使用社区活跃维护的 @faker-js/faker 分支;同时,casualchance 均已停止更新或被标记为弃用,不建议在新项目中使用。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
randexp6,925,4691,871-148 年前MIT
faker2,298,380-10.1 MB--MIT
chance2,139,0476,5572.13 MB1779 个月前MIT
casual293,4393,017-417 年前MIT

JavaScript 数据模拟工具深度对比:casual、chance、faker 与 randexp

在前端开发中,无论是搭建原型、编写测试用例,还是进行本地开发调试,我们常常需要生成逼真的假数据。casualchancefakerrandexp 是四个广泛使用的 npm 包,但它们的定位、能力边界和适用场景大不相同。本文将从实际工程角度出发,深入剖析它们的技术特性与取舍。

🧪 核心功能定位:通用数据 vs 正则表达式

首先需要明确一点:randexp 与其他三个包不在同一维度上

  • casualchancefaker 都是通用假数据生成器,提供姓名、地址、邮箱、电话、日期等常见字段的模拟。
  • randexp 则是一个正则表达式反向生成器 —— 它根据你提供的正则表达式,生成一个符合该规则的随机字符串。

这意味着 randexp 通常不会单独使用,而是作为其他假数据工具的补充,用于生成特定格式的字符串(如车牌号、产品编码等)。

// randexp: 根据正则生成字符串
import RandExp from 'randexp';

const licensePlate = new RandExp(/[A-Z]{3}-\d{4}/).gen();
// 例如: "XYZ-5821"

而其他三个包则直接提供高层语义接口:

// faker: 生成中文姓名
import { faker } from '@faker-js/faker';
faker.locale = 'zh_CN';
console.log(faker.name.fullName()); // 例如: "张伟"

// chance: 生成美国电话号码
import Chance from 'chance';
const chance = new Chance();
console.log(chance.phone()); // 例如: "(555) 555-5555"

// casual: 生成英文地址
import casual from 'casual';
console.log(casual.address); // 例如: "791 Crist Parks"

🌍 国际化支持:谁更适合中文项目?

对于面向中国市场的应用,本地化假数据至关重要。

faker(特指 @faker-js/faker,即社区维护的活跃分支)原生支持多语言,包括简体中文(zh_CN)。你可以轻松切换 locale,生成符合本地习惯的姓名、地址、公司名等。

// @faker-js/faker 支持中文
import { faker } from '@faker-js/faker';
faker.setLocale('zh_CN');

console.log(faker.name.lastName());   // 例如: "李"
console.log(faker.address.city());    // 例如: "北京市"
console.log(faker.company.name());    // 例如: "华为技术有限公司"

chancecasual 不支持国际化。它们的数据集主要基于英语/美国习惯。例如,chance.name() 只会生成西方人名(如 "John Doe"),casual.address 也是美式地址格式。若强行用于中文项目,会显得非常不真实。

⚠️ 注意:原始 faker(由 Marak 维护)已于 2021 年被标记为“不再维护”,并因恶意代码事件失去信任。当前推荐使用社区分叉版本 @faker-js/faker,它积极维护且功能更强大。

🔧 API 设计与扩展性

faker:模块化 + 高度可定制

@faker-js/faker 采用模块化设计,支持按需导入,减少打包体积。同时,它允许你通过 define 方法注册自定义方法,或覆盖现有行为。

// 自定义方法
faker.helpers.define('chineseIdCard', () => {
  // 实现身份证生成逻辑
  return '11010119900307XXXX';
});

console.log(faker.chineseIdCard());

chance:面向对象 + 可复用实例

chance 使用构造函数创建实例,适合需要隔离种子(seed)或多配置共存的场景。例如,在测试中为不同用户生成确定性数据。

const user1 = new Chance(123);
const user2 = new Chance(456);

console.log(user1.email()); // 每次运行结果一致
console.log(user2.email()); // 与 user1 不同,但自身稳定

casual:全局单例 + 简洁语法

casual 直接暴露一个全局对象,使用最简单,但缺乏隔离性。所有调用共享同一状态,不适合需要确定性或并行生成的场景。

import casual from 'casual';
console.log(casual.email); // 属性式访问,无括号

randexp:单一职责 + 与正则结合

randexp 只做一件事:从正则生成字符串。但它可以与其他假数据工具结合,增强表达力。

// 结合 faker 生成符合特定格式的 SKU
import { faker } from '@faker-js/faker';
import RandExp from 'randexp';

faker.helpers.define('productSku', () => {
  const prefix = faker.commerce.department().substring(0, 3).toUpperCase();
  const suffix = new RandExp(/\d{5}/).gen();
  return `${prefix}-${suffix}`;
});

console.log(faker.productSku()); // 例如: "ELE-48291"

⚠️ 维护状态与安全性

  • @faker-js/faker:活跃维护,社区驱动,定期发布新版本,安全记录良好。
  • chance:npm 页面显示 “This package has been deprecated”,但 GitHub 仓库仍在缓慢更新。不建议用于新项目
  • casual:GitHub 仓库多年未更新(最后提交在 2018 年),已事实废弃,存在潜在安全风险。
  • randexp:虽不频繁更新,但功能稳定,无已知严重漏洞,仍可用于特定场景。

🛑 重要提示casual 和原始 faker(非 @faker-js/faker不应在新项目中使用。前者已停止维护,后者存在历史安全问题。

📊 功能对比速查表

特性@faker-js/fakerchance (已弃用)casual (已废弃)randexp
中文支持✅ 原生 zh_CN❌ 仅英文❌ 仅英文❌ (不适用)
API 风格函数调用 + 模块化实例方法全局属性构造函数 + .gen()
可扩展性define() 自定义⚠️ 有限⚠️ 通过覆盖属性❌ 单一功能
确定性生成✅ 支持 seed✅ 实例隔离❌ 全局随机✅ 支持 seed
维护状态✅ 活跃⚠️ 已弃用❌ 停止维护✅ 稳定
典型用途全面假数据(推荐首选)老项目兼容避免使用正则匹配字符串生成

💡 实战建议

  • 新项目首选 @faker-js/faker:功能全面、支持中文、持续维护、社区活跃。
  • 需要生成特定格式字符串?randexpfaker 结合使用,发挥各自优势。
  • 避免使用 casualchance:前者已多年未更新,后者已被官方标记弃用,存在兼容性和安全风险。
  • 不要混淆 faker@faker-js/faker:务必安装后者,前者已不可信。

🔄 迁移示例:从 casual 到 @faker-js/faker

// 旧代码 (casual)
import casual from 'casual';
const user = {
  name: casual.name,
  email: casual.email,
  address: casual.address
};

// 新代码 (@faker-js/faker)
import { faker } from '@faker-js/faker';
faker.setLocale('zh_CN');

const user = {
  name: faker.name.fullName(),
  email: faker.internet.email(),
  address: `${faker.address.city()}${faker.address.streetAddress()}`
};

总结

选择假数据工具,不能只看“能不能生成”。维护状态、本地化支持、API 设计和长期可维护性才是工程决策的关键。

  • 真实、安全、可扩展 → 选 @faker-js/faker
  • 生成正则匹配的字符串 → 用 randexp 辅助
  • casualchance留在历史中,不要带入新项目

如何选择: randexp vs faker vs chance vs casual

  • randexp:

    当你需要根据正则表达式生成符合特定格式的字符串(如车牌、订单号、产品编码)时,选用 randexp。它不提供高层语义数据(如姓名、地址),但可与 @faker-js/faker 结合使用,弥补后者在格式化字符串生成上的不足。

  • faker:

    选择 @faker-js/faker(注意不是原始 faker 包)作为新项目的首选。它活跃维护、支持多语言(包括简体中文)、API 模块化且可扩展性强,适合需要真实感假数据的各类场景,从单元测试到本地开发均可胜任。

  • chance:

    chance 已被 npm 标记为弃用(deprecated),尽管 GitHub 仍有零星更新,但不再推荐用于新项目。如果你在维护一个老项目且暂时无法迁移,可继续使用,但应制定替换计划。

  • casual:

    不要在新项目中使用 casual。该库自 2018 年起已停止维护,GitHub 仓库多年无更新,存在潜在安全风险和兼容性问题。即使其 API 简洁,也应优先考虑现代替代方案。

randexp的README

randexp.js

randexp will generate a random string that matches a given RegExp Javascript object.

Build Status Dependency Status codecov

Usage

const RandExp = require('randexp');

// supports grouping and piping
new RandExp(/hello+ (world|to you)/).gen();
// => hellooooooooooooooooooo world

// sets and ranges and references
new RandExp(/<([a-z]\w{0,20})>foo<\1>/).gen();
// => <m5xhdg>foo<m5xhdg>

// wildcard
new RandExp(/random stuff: .+/).gen();
// => random stuff: l3m;Hf9XYbI [YPaxV>U*4-_F!WXQh9>;rH3i l!8.zoh?[utt1OWFQrE ^~8zEQm]~tK

// ignore case
new RandExp(/xxx xtreme dragon warrior xxx/i).gen();
// => xxx xtReME dRAGON warRiOR xXX

// dynamic regexp shortcut
new RandExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i');
// is the same as
new RandExp(new RegExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i'));

If you're only going to use gen() once with a regexp and want slightly shorter syntax for it

const randexp = require('randexp').randexp;

randexp(/[1-6]/); // 4
randexp('great|good( job)?|excellent'); // great

If you miss the old syntax

require('randexp').sugar();

/yes|no|maybe|i don't know/.gen(); // maybe

Motivation

Regular expressions are used in every language, every programmer is familiar with them. Regex can be used to easily express complex strings. What better way to generate a random string than with a language you can use to express the string you want?

Thanks to String-Random for giving me the idea to make this in the first place and randexp for the sweet .gen() syntax.

Default Range

The default generated character range includes printable ASCII. In order to add or remove characters, a defaultRange attribute is exposed. you can subtract(from, to) and add(from, to)

const randexp = new RandExp(/random stuff: .+/);
randexp.defaultRange.subtract(32, 126);
randexp.defaultRange.add(0, 65535);
randexp.gen();
// => random stuff: 湐箻ໜ䫴␩⶛㳸長���邓蕲뤀쑡篷皇硬剈궦佔칗븛뀃匫鴔事좍ﯣ⭼ꝏ䭍詳蒂䥂뽭

You can also change the default range by changing RandExp.prototype.defaultRange.

Custom PRNG

The default randomness is provided by Math.random(). If you need to use a seedable or cryptographic PRNG, you can override RandExp.prototype.randInt or randexp.randInt (where randexp is an instance of RandExp). randInt(from, to) accepts an inclusive range and returns a randomly selected number within that range.

Infinite Repetitionals

Repetitional tokens such as *, +, and {3,} have an infinite max range. In this case, randexp looks at its min and adds 100 to it to get a useable max value. If you want to use another int other than 100 you can change the max property in RandExp.prototype or the RandExp instance.

const randexp = new RandExp(/no{1,}/);
randexp.max = 1000000;

With RandExp.sugar()

const regexp = /(hi)*/;
regexp.max = 1000000;

Bad Regular Expressions

There are some regular expressions which can never match any string.

  • Ones with badly placed positionals such as /a^/ and /$c/m. Randexp will ignore positional tokens.

  • Back references to non-existing groups like /(a)\1\2/. Randexp will ignore those references, returning an empty string for them. If the group exists only after the reference is used such as in /\1 (hey)/, it will too be ignored.

  • Custom negated character sets with two sets inside that cancel each other out. Example: /[^\w\W]/. If you give this to randexp, it will return an empty string for this set since it can't match anything.

Projects based on randexp.js

JSON-Schema Faker

Use generators to populate JSON Schema samples. See: jsf on github and jsf demo page.

Install

Node.js

npm install randexp

Browser

Download the minified version from the latest release.

Tests

Tests are written with mocha

npm test

Integration with TypeScript

RandExp includes TypeScript definitions.

import * as RandExp from "randexp";
const randexp = new RandExp(/[a-z]{6}/);
randexp.gen();

Use dtslint to check the definition file.

npm install -g dtslint
npm run dtslint