How to generate mock data within seconds using Node.js to use in any application
Tags: javascript, node, codenewbie, react
Published: 2020-08-20 06:17:46

### Introduction

In most of the applications, you need to have some static JSON data with which you can create and test the application without directly using the production data.

If you’re building an e-commerce application, you may need a list of product details with the product name, image, and price to test.

If you want to showcase something then first you will need some data to display on the UI.

> Faker has around 1.4M weekly downloads (as of 20 August, 2020).

![Faker library](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/e1e0d01e7d6d75123c0de8d79797ab11dc234e3d/fk_.png)

So in this tutorial, you will see how to easily generate any amount of required data using a very popular npm library `faker`.

**Update: Faker npm package is no longer available. Instead you can use [faker-js](https://github.com/faker-js/faker) which is similar to faker.**

## Prerequisites

You will need the following to complete this tutorial:

* Node.js installed locally

This tutorial was verified with `Node` v13.14.0, `npm` v6.14.4, `faker` v4.1.0, `express` v4.17.1, `lodash` v4.17.19 and `nodemon` v2.0.4

## Installation

To install the library and other dependencies execute the following command from the terminal:

```js
npm install faker@4.1.0 express@4.17.1 lodash@4.17.19 nodemon@2.0.4
```

Import the library in the following way

```js
const faker = require('faker');
```

## Using APIs

Following are some of the API categories provided by the library

* address
* commerce
* company
* database
* finance
* hacker
* helpers
* image

Each category provides various functions to access the data.

### Get random country, city, state and zip code:

```js
const country = faker.address.country(); // Singapore
const city = faker.address.city(); // Laverneberg
const state = faker.address.state(); // West Virginia
const zipCode =  faker.address.zipCode(); // 57449-4128
```

### Get random product name, price and color:

```js
const product = faker.commerce.product(); // Table
const price = faker.commerce.price(); // 458.00
const color = faker.commerce.color(); // Cyan
```

Let’s build a simple application in Node.js where you provide a count of records you want and the application will generate that much data in the JSON format.

## Initial Setup

Create a new folder `mock-json-data-generator` and initialize the `package.json` file

```js
mkdir mock-json-data-generator
cd mock-json-data-generator
npm init -y
```

Now, install the `faker` , `lodash`, `express` and `nodemon` npm libraries


- `faker` will be used to generate random mock data 
- `lodash` will be used to execute a function for a certain number of times
- `express` will be used to create REST APIs
- `nodemon` will be used to restart the Express server if any file content is changed

Execute the following command from the `mock-json-data-generator` folder:

```js
npm install faker@4.1.0 lodash@4.17.19 express@4.17.1 nodemon@2.0.4
```

Add a new `start` script inside `package.json` file

```js
"scripts": {
 "start": "nodemon index.js"
}
```

Your `package.json` file will look like this now

![package.json](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/18382bcb31226cc87960e5073ca8ce0e03867918/pkg.png)

## Get a List of Random Addresses

Create a new `index.js` file and add the following code inside it:

```js
const express = require('express');
const faker = require('faker');
const _ = require('lodash');

const app = express();

app.get('/address', (req, res) => {
  const count = req.query.count;
  if (!count) {
    return res
      .status(400)
      .send({ errorMsg: 'count query parameter is missing.' });
  }
  res.send(
    _.times(count, () => {
      const address = faker.address;
      return {
        country: address.country(),
        city: address.city(),
        state: address.state(),
        zipCode: address.zipCode(),
        latitude: address.latitude(),
        longitude: address.longitude()
      };
    })
  );
});

app.listen(3030, () => {
  console.log('server started on port 3030');
});
```

In the above file, 

* First, we imported all the required packages
* Then created an express app by calling the `express` function

```js
const app = express();
```

* Then created a `/address` route
* Then we’re checking if the user has provided the `count` query parameter which specifies the number of records to get back

```js
const count = req.query.count;
  if (!count) {
    return res
      .status(400)
      .send({ errorMsg: 'count query parameter is missing.' });
  }
```

* If the `count` does not exist then we are displaying an error message
* Then we’re using the `times` method provided by `lodash` which will execute the provided function `count` number of times. Lodash library is optimized for performance so instead of using an array `map` method to generate for example 1000 records, we’re using `lodash` library so the response will be quicker.

```js
_.times(count, () => {
  const address = faker.address;
  return {
    country: address.country(),
    city: address.city(),
    state: address.state(),
    zipCode: address.zipCode(),
    latitude: address.latitude(),
    longitude: address.longitude()
  };
})
```
* The `times` method returns an array. In the provided arrow function, we’re returning an object with the randomly generated values so the output of `times` method will be an array of objects with the generated values.
* Then we’re sending that result using `send` method of response object using `res.send`
* Then at the end, we’re starting the `Express.js` server on port `3030`

```js
app.listen(3030, () => {
  console.log('server started on port 3030');
});
```

Now, start the application by executing the following command from the terminal:


```js
npm run start
```


and access the application by visiting http://localhost:3030/address?count=10

![Addresses](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/18382bcb31226cc87960e5073ca8ce0e03867918/addresses.png) <br />

> Tip: To get the formatted JSON as shown above, you can install the JSON Formatter Google Chrome extension.

If you don’t provide the `count` query parameter, then you will get an error as can be seen below.

![Missing query params](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/18382bcb31226cc87960e5073ca8ce0e03867918/missing.png)

## Get a List of Random Products

Add another `/products` route to get the list of products.

```js
app.get('/products', (req, res) => {
  const count = req.query.count;
  if (!count) {
    return res.status(400).send({
      errorMsg: 'count query parameter is missing.'
    });
  }
  res.send(
    _.times(count, () => {
      const commerce = faker.commerce;
      return {
        product: commerce.product(),
        price: commerce.price(),
        color: commerce.color()
      };
    })
  );
});
```

In this code, instead of `faker.address`, we’ve used `faker.commerce` and its related methods.

![Products](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/18382bcb31226cc87960e5073ca8ce0e03867918/products.png)

## Get a List of Random Images

Add another `/images` route to get the list of images.

```js
app.get('/images', (req, res) => {
  const count = req.query.count;
  if (!count) {
    return res.status(400).send({
      errorMsg: 'count query parameter is missing.'
    });
  }
  res.send(
    _.times(count, () => {
      const image = faker.image;
      return {
        image: image.image(),
        avatar: image.avatar()
      };
    })
  );
});
```

![Images](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/18382bcb31226cc87960e5073ca8ce0e03867918/images.png)

## Get a List of Random Words

Add another `/random` route to get the list of random words.

```js
app.get('/random', (req, res) => {
  const count = req.query.count;
  if (!count) {
    return res.status(400).send({
      errorMsg: 'count query parameter is missing.'
    });
  }
  res.send(
    _.times(count, () => {
      const random = faker.random;
      return {
        word: random.word(),
        words: random.words()
      };
    })
  );
});
```

In this code, we’ve used `faker.random` and its related methods.

![Words](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/18382bcb31226cc87960e5073ca8ce0e03867918/words.png)

## Get a List of Random Users

Add another `/users` route to get the list of random users.

```js
app.get('/users', (req, res) => {
  const count = req.query.count;
  if (!count) {
    return res.status(400).send({
      errorMsg: 'count query parameter is missing.'
    });
  }
  res.send(
    _.times(count, () => {
      const user = faker.name;
      return {
        firstName: user.firstName(),
        lastName: user.lastName(),
        jobTitle: user.jobTitle()
      };
    })
  );
});
```

In this code, we’ve used `faker.name` and its related methods.

![Random Users](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/18382bcb31226cc87960e5073ca8ce0e03867918/random_users.png)

## Get a List of Random Lorem Ipsum Text

Add another `/lorem` route to get the list of random lorem ipsum paragraphs.

```js
app.get('/lorem', (req, res) => {
  const count = req.query.count;
  if (!count) {
    return res.status(400).send({
      errorMsg: 'count query parameter is missing.'
    });
  }
  res.send(
    _.times(count, () => {
      const lorem = faker.lorem;
      return {
        paragraph: lorem.paragraph(),
        sentence: lorem.sentence(),
        paragraphs: lorem.paragraphs()
      };
    })
  );
});
```

In this code, we’ve used `faker.lorem` and its related methods.

![Lorem Ipsum](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/18382bcb31226cc87960e5073ca8ce0e03867918/lorem.png)

## Get a List of Random User Information

`Faker` library also provides a set of helpers like `createCard`, `userCard`, `createTransaction`.

Add another `/userCard` route to get the list of the random card of user information like name, email, address, website, company.

```js
app.get('/userCard', (req, res) => {
  const count = req.query.count;
  if (!count) {
    return res.status(400).send({
      errorMsg: 'count query parameter is missing.'
    });
  }
  res.send(
    _.times(count, () => {
      const helpers = faker.helpers;
      return {
        userCard: helpers.userCard()
      };
    })
  );
});
```

In this code, we’ve used `faker.helpers` and its `userCard` method.

![User Card](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/18382bcb31226cc87960e5073ca8ce0e03867918/userCard.png)

In addition to the above user details, If we want the user's posts and transaction details, we can use the `createCard` helper method

Add another `/createCard` route to get the data of users posts and transactions in addition to the other details

```js
app.get('/createCard', (req, res) => {
  const count = req.query.count;
  if (!count) {
    return res.status(400).send({
      errorMsg: 'count query parameter is missing.'
    });
  }
  res.send(
    _.times(count, () => {
      const helpers = faker.helpers;
      return {
        createCard: helpers.createCard()
      };
    })
  );
});
```

In this code, we’ve used `faker.helpers` and its `createCard` method.

![Create Card](https://gist.github.com/myogeshchavan97/e0be7fc4c838544e2d00afeb3a82ae10/raw/18382bcb31226cc87960e5073ca8ce0e03867918/createCard.png)

`Faker` provides a lot of other details which you can check at [this url](https://www.npmjs.com/package/faker).

## Conclusion

As you have seen, the `Faker` library provides a lot of API functions to easily generate random data. It’s also very useful when you want to build something quickly without wasting hours of time for creating the data to work with.

You can find the complete source code for this application [here](https://github.com/myogeshchavan97/mock-json-data-generator).

<br />

**Don't forget to subscribe to get my weekly newsletter with amazing tips, tricks and articles directly in your inbox [here](https://yogeshchavan.dev).**

[<img src="https://cdn.buymeacoffee.com/buttons/default-yellow.png" >](https://www.buymeacoffee.com/myogeshchavan97)