How to generate mock data within seconds using Node.js to use in any application

Yogesh Chavan - Aug 20 '20 - - Dev Community

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

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 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:



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


Enter fullscreen mode Exit fullscreen mode

Import the library in the following way



const faker = require('faker');


Enter fullscreen mode Exit fullscreen mode

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:



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


Enter fullscreen mode Exit fullscreen mode

Get random product name, price and color:



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


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

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:



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


Enter fullscreen mode Exit fullscreen mode

Add a new start script inside package.json file



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


Enter fullscreen mode Exit fullscreen mode

Your package.json file will look like this now

package.json

Get a List of Random Addresses

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



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');
});


Enter fullscreen mode Exit fullscreen mode

In the above file,

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


const app = express();


Enter fullscreen mode Exit fullscreen mode
  • 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


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


Enter fullscreen mode Exit fullscreen mode
  • 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.


_.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()
  };
})


Enter fullscreen mode Exit fullscreen mode
  • 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


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


Enter fullscreen mode Exit fullscreen mode

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



npm run start


Enter fullscreen mode Exit fullscreen mode

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

Addresses

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

Get a List of Random Products

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



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()
      };
    })
  );
});


Enter fullscreen mode Exit fullscreen mode

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

Products

Get a List of Random Images

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



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()
      };
    })
  );
});


Enter fullscreen mode Exit fullscreen mode

Images

Get a List of Random Words

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



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()
      };
    })
  );
});


Enter fullscreen mode Exit fullscreen mode

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

Words

Get a List of Random Users

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



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()
      };
    })
  );
});


Enter fullscreen mode Exit fullscreen mode

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

Random Users

Get a List of Random Lorem Ipsum Text

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



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()
      };
    })
  );
});


Enter fullscreen mode Exit fullscreen mode

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

Lorem Ipsum

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.



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()
      };
    })
  );
});


Enter fullscreen mode Exit fullscreen mode

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

User Card

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



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()
      };
    })
  );
});


Enter fullscreen mode Exit fullscreen mode

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

Create Card

Faker provides a lot of other details which you can check at this url.

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.

Don't forget to subscribe to get my weekly newsletter with amazing tips, tricks and articles directly in your inbox here.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .