In this article, we will generate mock data using the faker-js library.

Faker.js is a library that generates fake data like names, emails, addresses, and phone numbers. It is useful for generating mock data for testing or populating databases.

We will generate mock data for a list of 10 users. Each user will have an id, name, email, and phone number.

The generated mock data will be written to a file named using timestamp like mock-data-2022-03-31T12:00:00.json.

Install Node and npm

The following approach uses installation using nvm (Node Version Manager). Visit Node.js — Download Node.js® for more options.

# installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash

# download and install Node.js (you may need to restart the terminal)
nvm install 22

# verifies the right Node.js version is in the environment
node -v # should print `v22.12.0`

# verifies the right npm version is in the environment
npm -v # should print `10.9.0`

The printed versions may vary depending on the latest versions available at the time of installation.

Project Setup

In Terminal app, create a new project directory and navigate to it.

mkdir mock-data-generator
cd mock-data-generator

Initialize a new Node.js project

npm init -y

Install faker-js

npm install @faker-js/faker

Create a new file index.js. This file will contain the code to generate mock data.

touch index.js

Generate mock data

Add the following code to index.js to generate mock data for a list of 10 users.

const fs = require("fs");
const { faker } = require("@faker-js/faker");

// Function to generate mock data for a list of users
const generateMockData = (count) => {
    const mockData = [];

    for (let i = 0; i < count; i++) {
        const user = {
            id: faker.string.uuid(),
            name: faker.person.fullName(),
            email: faker.internet.email(),
            phone: faker.phone.number(),
        };
        mockData.push(user);
    }

    return mockData;
};

const mockData = generateMockData(10);
const fileName = `mock-data-${new Date().toISOString()}.json`;

// Write mock data to a file
fs.writeFileSync(fileName, JSON.stringify(mockData, null, 2));

console.log(`Generated ${mockData.length} mock users and saved to ${fileName}`);

Run the script using the following command

node index.js

This will generate mock data for 10 users and write it to a file. The file will be named using the current timestamp.

The terminal output will look like this

Generated 10 mock users and saved to mock-data-2024-12-23T09:06:26.024Z.json

The generated file will contain the mock data in JSON format.

[
    {
        "id": "f54f4781-0900-443a-823c-5400c0b277ae",
        "name": "Mr. Eric Bednar",
        "email": "Kailey.Bashirian-OReilly87@hotmail.com",
        "phone": "637.524.5603 x222"
    },
    ...
]

Common Faker.js methods

  • UUID: faker.string.uuid()

  • Full Name: faker.person.fullName()

  • First Name: faker.person.firstName()

  • Last Name: faker.person.lastName()

  • Email: faker.internet.email()

  • Phone Number: faker.phone.number()

  • Avatar: faker.image.avatar()

  • User Name: faker.internet.username()

  • Address: faker.address.streetAddress()

  • City: faker.address.city()

  • Country: faker.address.country()

  • Time Zone: faker.location.timeZone()

  • Job Title: faker.person.jobTitle()

  • Company Name: faker.company.name()

  • Boolean: faker.datatype.boolean()

  • Integer: faker.number.int({ min: 10, max: 100 })

  • Float: faker.number.float({ min: 20, max: 30 })

  • Date: faker.date.recent(), faker.date.past(), faker.date.future()

  • Color: faker.color.rgb()

  • Image: faker.image.url(), faker.image.urlPicsumPhotos(), faker.image.urlLoremFlickr()

  • Amount: faker.finance.amount()

  • Currency: faker.finance.currency()

  • URL: faker.internet.url()

  • Emoji: faker.internet.emoji()

  • Word: faker.lorem.word(), faker.lorem.words(10)

  • Sentences: faker.lorem.sentence(), faker.lorem.sentences(2, '\n')

  • Paragraph: faker.lorem.paragraph(), faker.lorem.paragraphs(2, '\n')

Refer to API Reference | Faker Open Collective for more methods.

This is how you can generate mock data using the faker-js library. You can customize the data generated based on your requirements to generate users, posts, products, or any other type of data for testing or development purposes.