8.4.1 • Published 20 days ago

@faker-js/faker v8.4.1

Weekly downloads
-
License
MIT
Repository
github
Last release
20 days ago

Try it Online ⚡️

fakerjs.dev/new

npm.io

Installation

Please replace your faker dependency with @faker-js/faker. This is the official, stable fork of Faker.

npm install @faker-js/faker --save-dev

or yarn

yarn add @faker-js/faker -D

or pnpm

pnpm install @faker-js/faker -D

Browser

<script src="faker.js" type="text/javascript"></script>
<script>
  const randomName = faker.name.findName(); // Caitlyn Kerluke
  const randomEmail = faker.internet.email(); // Rusty@arne.info
  const randomCard = faker.helpers.createCard(); // random contact card containing many properties
</script>

Node.js

const { faker } = require('@faker-js/faker');
const randomName = faker.name.findName(); // Rowan Nikolaus
const randomEmail = faker.internet.email(); // Kassandra.Haley@erich.biz
const randomCard = faker.helpers.createCard(); // random contact card containing many properties

CDN/Deno

import { faker } from 'https://cdn.skypack.dev/@faker-js/faker';

const randomName = faker.name.findName(); // Willie Bahringer
const randomEmail = faker.internet.email(); // Tomasa_Ferry14@hotmail.com
const randomCard = faker.helpers.createCard(); // random contact card containing many properties

TypeScript Support

Since version v6+ there is native TypeScript support.

In order to have faker working properly, you need to check if these compilerOptions are set correctly in your tsconfig file:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "moduleResolution": "Node"
  }
}

If you want for whatever reason the versions prior to v6, you can use @types/faker and rebind the declarations to the @faker-js/faker package with a faker.d.ts file in your e.g. src folder.

// faker.d.ts
declare module '@faker-js/faker' {
  import faker from 'faker';
  export default faker;
}

API

An in-depth overview of the API methods is available in the documentation. The API covers the following modules:

ModuleExampleOutput
Addressfaker.address.city()Lake Raoulfort
Animalfaker.animal.type()Dog, cat, snake, bear, lion, etc.
Commercefaker.commerce.product()Polo t-shirt
Companyfaker.company.companyName()Zboncak and Sons
Databasefaker.database.engine()MyISAM
Datatypefaker.datatype.uuid()1oijf8-3iuhiu-21jddj-1092jf
Datefaker.date.past()Sat Oct 20 2018 04:19:38 GMT-0700 (Pacific Daylight Time)
Financefaker.finance.amount()¥23400 (After setting locale)
Gitfaker.git.commitMessage()feat: add products list page
Hackerfaker.hacker.phrase()Try to reboot the SQL bus, maybe it will bypass the virtual application!
Helpersfaker.helpers.userCard(){ avatar: '...', email: '{ first }{ last }{ number }@{domain}', first: '...' }All of the values are self-consistent (e.g. same first + last name in the email, too)
Imagefaker.image.avatar()https://cloudflare-ipfs.com/ipfs/Qmd3W5DuhgHirLHGVixi6V76LhCkZUz6pnFt5AJBiyvHye/avatar/233.jpg
Internetfaker.internet.color()#630c7b
Loremfaker.lorem.paragraph()Word, words, sentences, slug (lorem-ipsum), paragraph(s), text, lines
Musicfaker.music.genre()R&B
Namefaker.name.firstName()Cameron
Phonefaker.phone.phoneNumber()+1 291-299-0192
Randomfaker.random.locale()fr_CA
Systemfaker.system.directoryPath()C:\Documents\Newsletters\
Vehiclefaker.vehicle.vehicle()2011 Dodge Caravan

API Methods

Faker provides many useful utility functions.

  • faker.address

    APIDescription
    zipCodeGet fake zip code
    zipCodeByStateGet fake zip code by state
    cityGet fake city
    cityPrefixGet fake city prefix
    citySuffixGet fake city suffix
    cityNameGet fake city name
    streetNameGet fake street name
    streetAddressGet fake street address
    streetSuffixGet fake street suffix
    streetPrefixGet fake street prefix
    secondaryAddressGet fake secondary address
    countyGet fake county
    countryGet fake country
    countryCodeGet fake country code
    stateGet fake state
    stateAbbrGet fake state abbreviation
    latitudeGet fake latitude
    longitudeGet fake longitude
    directionGet fake direction
    cardinalDirectionGet fake cardinal direction
    ordinalDirectionGet fake ordinal direction
    nearbyGPSCoordinateGet fake near by gps coordinate
    timeZoneGet fake timezone
  • faker.animal

    APIDescription
    dogGet fake dog type
    catGet fake cat type
    snakeGet fake snake type
    bearGet fake bear type
    lionGet fake lion type
    cetaceanGet fake cetacean type
    horseGet fake horse type
    birdGet fake bird type
    cowGet fake cow type
    fishGet fake fish type
    crocodiliaGet fake crocodilia type
    insectGet fake insect type
    rabbitGet fake rabbit type
  • faker.commerce

    APIDescription
    colorGet fake color name
    departmentGet fake department name
    productNameGet fake product name
    priceGet fake price count
    productAdjectiveGet fake product adjective
    productMaterialGet fake product material data
    productGet fake product name
    productDescriptionGet fake product description
  • faker.company

    APIDescription
    suffixesGet fake company suffixes
    companyNameGet fake company name
    companySuffixGet fake company suffix
    bsGet fake company business services
    catchPhraseAdjectiveGet fake product adjective
    catchPhraseDescriptorGet fake product material data
    catchPhraseNounGet fake product name
    bsAdjectiveGet fake business services adjective
    bsBuzzGet fake business services buzz
    bsNounGet fake business services noun
  • faker.database

    APIDescription
    columnGet fake database column name
    typeGet fake database column datatype
    collationGet fake database collation
    engineGet fake database engine
  • faker.datatype

    APIDescription
    numberGenerates a random number
    floatGenerates a random floating number
    datetimeGenerates a random datetime
    stringGenerates a random string
    uuidGenerates a valid uuid
    booleanGenerates a boolean
    hexaDecimalGenerates a hexadecimal
    jsonGenerates a valid json object
    arrayGenerates an array
  • faker.date

    APIDescription
    pastGet a date N years into the past
    futureGet a date N years into the future
    betweenGet a random date between the dates given
    betweensGet an array of 3 dates ( by default ) of sorted randoms dates between the dates given
    recentGet a date N days from the recent past
    soonGet a date N days into the future
    monthGenerates a random value of date month
    weekdayGenerates a random value of date weekday
  • faker.fake

  • faker.finance

    APIDescription
    accountGenerates a random finance account
    accountNameGenerates a random finance account name
    routingNumberGenerates a random finance routing number
    maskGenerates a random finance mask template
    amountGenerates a random amount of transaction
    transactionTypeGenerates a random transaction type
    currencyCodeGenerates a random currency code
    currencyNameGenerates a random currency name
    currencySymbolGenerates a random currency symbol
    bitcoinAddressGenerates a random bitcoin address
    litecoinAddressGenerates a random litecoin address
    creditCardNumberGenerates a random credit card number
    creditCardCVVGenerates a random credit card CVV
    ethereumAddressGenerates a random ethereum address (ETH address)
    ibanGenerates a random IBAN
    bicGenerates a random BIC
    transactionDescriptionGenerates a random transaction description
  • faker.git

    APIDescription
    branchGenerates a random branch with hacker noun and verb
    commitEntryGenerates a random commit entry with git commit message and sha
    commitMessageGenerates a random commit message with hacker noun, adj and verb
    commitShaGenerates a random commit SHA
    shortShaGenerates a random short SHA
  • faker.hacker

    APIDescription
    abbreviationGenerates a random hacker abbreviation
    adjectiveGenerates a random hacker adjective
    nounGenerates a random hacker noun
    verbGenerates a random hacker verb
    ingverbGenerates a random hacker ingverb
    phraseGenerates a random hacker phrase
  • faker.helpers

    APIDescription
    randomizeGet a random element from an array
    slugifyRemoves unwanted characters from URI string
    replaceSymbolWithNumberParses string for a symbol and replace it with a random number from 1-10
    replaceSymbolsParses string for symbols (numbers or letters) and replaces them appropriately (# will be replaced with number, ? with letter and * will be replaced with number or letter)
    replaceCreditCardSymbolsReplace symbols in a credit card schema including Luhn checksum
    repeatStringString repeat helper, alternative to String.prototype.repeat
    shuffleTakes an array and randomizes it in place then returns it using the modern version of the Fisher-Yates algorithm
    mustacheGenerates a string with mustache {{ }}
    createCardGenerates a human card
    contextualCardGenerates a human contextual card
    userCardGenerates a website user card
    createTransactionGenerates a transaction
  • faker.image

    APIDescription
    imageGenerates a random image
    avatarGenerates a random avatar
    imageUrlGenerates a random image url
    abstractGenerates a random abstract image
    animalsGenerates a random animals image
    businessGenerates a random business image
    catsGenerates a random cats image
    cityGenerates a random city image
    foodGenerates a random food image
    nightlifeGenerates a random nightlife image
    fashionGenerates a random fashion image
    peopleGenerates a random people image
    natureGenerates a random nature image
    sportsGenerates a random sports image
    technicsGenerates a random technics image
    transportGenerates a random transport image
    dataUriGenerates a random data uri
    lorempixelGenerates a random image url from lorempixel
    unsplashGenerates a random image url from unsplash
    lorempicsumGenerates a random image url from lorem picsum
  • faker.internet

    APIDescription
    avatarGenerates a random avatar
    emailGenerates a random email
    exampleEmailGenerates a random example email
    userNameGenerates a random user name
    protocolGenerates a random internet protocol (http or https)
    httpMethodGenerates a random http method
    urlGenerates a random url
    domainNameGenerates a random domain name
    domainSuffixGenerates a random domain suffix
    domainWordGenerates a random domain word
    ipGenerates a random ip
    ipv6Generates a random ipv6
    portGenerates a random port number
    userAgentGenerates a random user agent
    colorGenerates a random hexadecimal color
    macGenerates a random mac address
    passwordGenerates a random password
  • faker.lorem

    APIDescription
    wordGenerates a random lorem word
    wordsGenerates a random lorem words
    sentenceGenerates a random lorem sentence
    slugGenerates a random lorem slug
    sentencesGenerates a random lorem sentences
    paragraphGenerates a random lorem paragraph
    paragraphsGenerates a random lorem paragraphs
    textGenerates a random lorem text
    linesGenerates a random lorem lines
  • faker.mersenne

    APIDescription
    randGenerates a random mersenne rand
    seedGenerates a random mersenne seed
    seed_arrayGenerates a random datetime seed init by array
  • faker.music

    APIDescription
    genreGenerates a random music genre
  • faker.name

    APIDescription
    firstNameGenerates a random human first name
    lastNameGenerates a random human last name
    middleNameGenerates a random human middle name
    findNameGenerates a random human first name and last name
    jobTitleGenerates a random human job title, combination of jobDescriptor, jobArea and jobType
    genderGenerates a random gender
    prefixGenerates a random locale with gender specific name prefix
    suffixGenerates a random locale with gender specific name suffix
    titleGenerates a random human title
    jobDescriptorGenerates a random human job descriptor
    jobAreaGenerates a random human job area
    jobTypeGenerates a random human job type
  • faker.phone

    APIDescription
    phoneNumberGenerates a random phone number
    phoneNumberFormatGenerates a random phone number with requested format (Array index)
    phoneFormatsGenerates a random phone number format
  • faker.random

    APIDescription
    arrayElementTakes an array and returns a random element of the array
    arrayElementsTakes an array and returns a subset with random elements of the array
    objectElementTakes an object and returns a random key or value
    wordGenerates a random word
    wordsGenerate N random words, with N defaulting to a random number between 1 and 3
    localeGenerates a random locale
    alphaGenerates lower/upper alphabetic characters
    alphaNumericGenerates alphanumeric characters
  • faker.system

    APIDescription
    fileNameGenerates a random filenames without system path separators
    commonFileNameGenerates a random filenames without system path separators
    mimeTypeGenerates a random mimetypes
    commonFileTypeGenerates a random commonly used file type
    commonFileExtGenerates a random commonly used file extension
    fileTypeGet any file type available as mime-type
    fileExtGenerates a random file extension
    directoryPathGenerates a random directory path
    filePathGenerates a random unix fs file full path
    semverGenerate semantic version
  • faker.time

    APIDescription
    recentGet recent timestamp in Unix time format
  • faker.unique

  • faker.vehicle

    APIDescription
    vehicleGenerates a random vehicle name
    manufacturerGenerates a random vehicle manufacturer name
    modelGenerates a random vehicle model name
    typeGenerates a random vehicle type
    fuelGenerates a random vehicle fuel type
    vinGenerates a random vehicle vin number
    colorGenerates a random vehicle color
    vrmGenerates a random vehicle vrm
    bicycleGenerates a random bicycle type

Faker.fake()

Faker contains a super useful generator method Faker.fake for combining faker API methods using a mustache string format.

Example:

console.log(
  faker.fake('{{name.lastName}}, {{name.firstName}} {{name.suffix}}')
);

This will interpolate the format string with the value of methods name.lastName(), name.firstName(), and name.suffix()

Localization

Faker has support for multiple locales.

The default language locale is set to English.

Setting a new locale is simple:

// sets locale to de
faker.locale = 'de';

See our documentation for a list of provided languages

Individual Localization Packages

Faker supports incremental loading of locales.

// loads only de locale
const faker = require('@faker-js/faker/locale/de');

Setting a randomness seed

If you want consistent results, you can set your own seed:

faker.seed(123);

const firstRandom = faker.datatype.number();

// Setting the seed again resets the sequence.
faker.seed(123);

const secondRandom = faker.datatype.number();

console.log(firstRandom === secondRandom);

Contributing

Building Faker

The project is being built by esbuild (see bundle.ts)

pnpm install
pnpm run build

Testing

pnpm install
pnpm run build

pnpm run test
# or
pnpm run coverage

You can view a code coverage report generated in coverage/index.html.

Developing the docs

# build the Faker dist
# it's used inside of certain routes
pnpm run build

pnpm run docs:dev

Building and serving the docs statically

# build the Faker dist
# it's used inside of certain routes
pnpm run build

pnpm run docs:build # Output docs to /dist
pnpm run docs:serve # Serve docs from /dist

Deploying Documentation

The website is kindly hosted for free by the Netlify team under their Open Source plan. See the netlify.toml for configuration.

What happened to the original faker.js?

Read the team update (January 14th, 2022).

@xata.io/importer@cegal/ds-graph@mikro-orm/seeder@procore/labs-coordination-issue-panel@procore/labs-observation-panel@procore/labs-rfi-panel@spaceone/design-system@sleekcms/cms-snapshot-data@pingux/astro@dxos/feed-store@dxos/clibys-container@dxos/react-client@thingspro-cloud/sdktool-bolideai-ui-kitobjection-foundrygen-db-data@lugg/utils@redcap-konex/neat-orm@redocly/christi@jeroboby/nestjs-package-starterirest_testad-data-fakervendorstack-backend-bank-paymentsvendorstack-backend-businessesvendorstack-backend-categories-tagsvendorstack-backend-ordersvendorstack-backend-sharedvendorstack-backend-userstool-microfrontend-shared-state@textea/yodasgenerator-jhipster-wda@natewilcox/servicespiper-faker@everything-registry/sub-chunk-312@declanprice/noxatmforumtmforum-newbys-container-ui2mg-faker@daddyjanno/table-componentguna-tmfrafsun-core-services@digital-alchemy/sampler-appdydev-utilsroot-utilsgithub-actions-clientgitaristgrunt-template-partsirest-appirest-app-testitrumitrum-uijoifakerhash-honeypothaven-componentshummingbird-componentgraphql-codegen-typescript-mock-datagqlfakegraphql-demeter-coregraphql-fake-data-generatorgraphql-fakergraphql-mock-data-generatorgrockerygenerator-jhipstergenerator-jhipster-darylgraphql-codegen-faker-fixturesjson-generate-toolkafka-datagen-testhyoopmybankibadkath-bankhello-mavfhellointechellointec1980hellointec2022hellozaqouthealthoneheets-coreh5-atmhigh-performance-utilsiot885-plugin-coreiuremagnamkj07-my-bankkubitkraken-nodem16rifle_atm_intrectivem6ra10-my-bankm-adil-atmlumisgraphql-fixturesinsomnia-plugin-fakerinsomnia-plugin-fakeinsomnia-plugin-quicky-fake-data-generationhyponoe-nonretail-backendi-functionhyperstackinitbacknodejsintermock-ssgimagebridge-nodejslechonk
9.0.0-alpha.0

20 days ago

8.4.1

3 months ago

8.4.0

3 months ago

8.1.0

8 months ago

8.3.0

6 months ago

8.3.1

6 months ago

8.2.0

7 months ago

8.0.0-alpha.1

1 year ago

8.0.0-alpha.2

1 year ago

8.0.0-beta.0

1 year ago

8.0.0-beta.1

12 months ago

8.0.1

12 months ago

8.0.0

12 months ago

8.0.2

11 months ago

8.0.0-alpha.0

1 year ago

7.6.0

2 years ago

7.3.0

2 years ago

7.4.0

2 years ago

7.5.0

2 years ago

7.0.0

2 years ago

7.2.0

2 years ago

7.1.0

2 years ago

7.0.1

2 years ago

6.3.0

2 years ago

6.3.1

2 years ago

6.2.0

2 years ago

6.1.2

2 years ago

6.1.0

2 years ago

6.0.0

2 years ago

6.1.1

2 years ago

6.0.0-beta.0

2 years ago

6.0.0-alpha.7

2 years ago

6.0.0-alpha.6

2 years ago

6.0.0-alpha.5

2 years ago

6.0.0-alpha.4

2 years ago

6.0.0-alpha.3

2 years ago

6.0.0-alpha.2

2 years ago

5.5.3

2 years ago

5.5.2

2 years ago

5.5.1

2 years ago

5.5.0

2 years ago

5.4.0

2 years ago

5.3.1

2 years ago

5.3.0

2 years ago

5.2.0

2 years ago

5.1.0

2 years ago

5.0.0

2 years ago

4.1.0

2 years ago

4.0.0

2 years ago

3.1.0

2 years ago

3.0.1

2 years ago

3.0.0

2 years ago

2.1.5

2 years ago

2.1.4

2 years ago

2.1.3

2 years ago

2.1.2

2 years ago

2.1.1

2 years ago

2.1.0

2 years ago

2.0.3

2 years ago

2.0.1

2 years ago

1.1.0

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago