Create Fake Data Easily Using JavaScript

Published: 2021-05-13 07:07:47

Ever need to populate a table or generate some data to see what your GUI looks like when it’s in use? Need to test the performance of your application under load? Have to do a demo but you don’t have any legitimate data to do the demo as it’s pre-release?

Usually in this scenario, a programmer has one of two options:

1.  Manually input the data by hand
2.  Code your own seeding application that does it all for you

Neither of these scenarios are ideal. Manually inputting data by hand can take time, a lot of time. Coding your own seeding application is not as easy as you’d think, you need to understand the process of  [generating random text](https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript), dummy images, random dates, names, emails, etc.

# What is Faker.js

Introducing  [Faker.js](https://github.com/marak/Faker.js/)  a brilliant solution to help you generate data and seed your application. Faker.js can be used either in the browser, or using node.js. All the problems and quirks with generating random data – some listed above – have been thought of and solved in Faker, so we don’t need to spend any more time reinventing the wheel.

# Generating User Data

The most common scenario I can think of – and was required at work just a couple weeks ago – is generating User data. Let’s create a dummy node app that has a  `GET/ users`  request that’ll return a list of generated users. For the sake of this blog I’ll leave out the complexities of pagination, I’ll just return an array of 100 users.

```javascript
const express = require("express");
const app = express();
app.listen(3000, () => {
 console.log("Server running on port 3000");
});

app.get("/users", (req, res, next) => {
    res.json([
        {
            "name": "Douglas Adams",
            "email": "douglas@gmail.com",
            "postcode": "pe22 22a",
            "phoneNumber": "07428233312",
            "city": "London",
            "country": "England",
            "favouriteQuote": "The answer is 42"
        }
    ]);
});
```
So if we call the endpoint  `GET  http://localhost:3000/users`:

**Response**:

```json
[
    {
        "name": "Douglas Adams",
        "email": "douglas@gmail.com",
        "postcode": "pe22 22a",
        "phoneNumber": "07428233312",
        "city": "London",
        "country": "England",
        "favouriteQuote": "The answer is 42"
    }
]
```
This is the basic format of the data we want to generate. Let’s make use of Faker to do this for us.

Faker is super simple, all you need to do is scan their  [README.md](https://github.com/Marak/faker.js)  for a good understanding of how they’ve structured it. Basically, there’s a list of objects that you can reference and each of those objects have methods that you can call. For example, there’s an  `address`  which has methods such as:

```none
zipCode()
zipCodeByState()
city()
cityPrefix()
citySuffix()
// and a load more
```
So to get a random zip code I’d simply need to make the following call:

```javascript
faker.address.zipCode()
```
Let’s incorporate this into our code:

`npm install faker`

```javascript
const express = require("express");
const faker = require('faker');
const app = express();
app.listen(3000, () => {
 console.log("Server running on port 3000");
});

app.get("/users", (req, res, next) => {
    res.json([
        {
            "name": faker.name.findName(),
            "email": faker.internet.email(),
            "postCode": faker.address.zipCode(),
            "city": faker.address.cityName(),
            "country": faker.address.country(),
            "phoneNumber": faker.phone.phoneNumber(),
            "favouriteQuote": faker.lorem.sentence()
        }
    ]);
});
```
So now when I make the request, the response it returns is:

```json
[
    {
        "name": "Darnell Marquardt",
        "email": "Braden_Block@gmail.com",
        "postCode": "56653",
        "city": "Mount Vernon",
        "country": "Paraguay",
        "phoneNumber": "987-214-5854 x674",
        "favouriteQuote": "Harum veritatis est dolore amet nam debitis."
    }
]
```
And if I run it again I’ll get a different result:

```json
[
    {
        "name": "Victoria Kerluke V",
        "email": "Valentin.Beahan@hotmail.com",
        "postCode": "15058",
        "city": "Kendall",
        "country": "Serbia",
        "phoneNumber": "751.325.8108 x50407",
        "favouriteQuote": "Deserunt rerum maiores."
    }
]
```
Next, let’s update the code so it actually returns an array of 100 users:

```javascript
app.get("/users", (req, res, next) => {
    res.json(getUsers());
});

function getUsers() {
    let users = [];
    for (let i = 0; i < 100; i++) {
        users.push({
            "name": faker.name.findName(),
            "email": faker.internet.email(),
            "postCode": faker.address.zipCode(),
            "city": faker.address.cityName(),
            "country": faker.address.country(),
            "phoneNumber": faker.phone.phoneNumber(),
            "favouriteQuote": faker.lorem.sentence()
        })
    }
    return users;
}

```

**Response:**

```json
[
    {
        "name": "Sandra Schaefer",
        "email": "Bethany12@yahoo.com",
        "postCode": "65665",
        "city": "Palm Harbor",
        "country": "Slovakia (Slovak Republic)",
        "phoneNumber": "379-607-0449",
        "favouriteQuote": "Qui consectetur repellendus commodi."
    },
    {
        "name": "Mark Veum",
        "email": "Jedediah.Beer26@yahoo.com",
        "postCode": "89859",
        "city": "Montebello",
        "country": "Myanmar",
        "phoneNumber": "779.494.2905 x0531",
        "favouriteQuote": "Corrupti assumenda enim alias suscipit maxime molestiae quis laboriosam."
    },
   // you get the idea..
```
# Using a seed

Let's imagine a scenario. You're doing a demonstration of the new users page, you click to open up the page, a GET users request is made, random users are returned. You spend a little time on the page, people become accustomed to the names of the users in the table. Then you come off the page to change some config. You go back to the page, a GET users request is made and  _different_  random users are returned, "What happened to Sandra" someone asks.

The thing that I love most about Faker, is that you can use a  [randomness seed](https://www.wikiwand.com/en/Random_seed)  meaning you can get consistent results every time you make a call. This is something that you most likely wouldn't implement if you were creating your own random data, well at least, I wouldn't.

Let's use a seed in our request:

```javascript
app.get("/users", (req, res, next) => {
    faker.seed(123);
    res.json(getUsers());
});
```

Now every time I make a request the same data gets returned:

**Going to the users page for the first time:**

```json
[
    {
        "name": "Clara Keebler",
        "email": "Maryse_Lubowitz49@gmail.com",
        "postCode": "79465",
        "city": "Lancaster",
        "country": "Burundi",
        "phoneNumber": "536.734.2063",
        "favouriteQuote": "Id harum sit odio quia vitae provident."
    },
    {
        "name": "Kristin Nicolas",
        "email": "Roslyn_Kulas61@gmail.com",
        "postCode": "74363",
        "city": "Guaynabo",
        "country": "Czech Republic",
        "phoneNumber": "496-807-4041",
        "favouriteQuote": "Sequi molestiae beatae enim necessitatibus molestiae."
    },
   // etc
```

**Coming back to the users page:**

```json
[
    {
        "name": "Clara Keebler",
        "email": "Maryse_Lubowitz49@gmail.com",
        "postCode": "79465",
        "city": "Lancaster",
        "country": "Burundi",
        "phoneNumber": "536.734.2063",
        "favouriteQuote": "Id harum sit odio quia vitae provident."
    },
    {
        "name": "Kristin Nicolas",
        "email": "Roslyn_Kulas61@gmail.com",
        "postCode": "74363",
        "city": "Guaynabo",
        "country": "Czech Republic",
        "phoneNumber": "496-807-4041",
        "favouriteQuote": "Sequi molestiae beatae enim necessitatibus molestiae."
    },
   // etc
```

# Summary

Generating random data is something all programmers will have to do at some point. With Faker.js it's an easier ride. Simply  `npm install`  for a node app or add it to your frontend solution. Need some data but don't have a backend to supply the data yet, then use faker.js.

I hope you've enjoyed this blog, if you do by some miracle enjoy my blabbering then head over to my blogging site at codeheir.com where I write weekly blogs about whatever in the world of programming has my attention!