How To Generate Various Types of Mock Data Within Seconds Using Node.js

How To Generate Various Types of Mock Data Within Seconds Using Node.js

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.

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 want to showcase something then first you will need some data to display on the UI.

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

Faker has around 1.7M weekly downloads (as of 2nd April, 2021).

faker.png

Update: Faker npm package is no longer available. Instead you can use faker-js which is similar to faker.

Installation

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

npm install faker express lodash nodemon

Import the library in the following way

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:

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:

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

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 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 lodash express nodemon

Add a new start script inside package.json file

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

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

In the above file,

  • First, we imported all the required packages
  • Then created an express app by calling the express function
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
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.
_.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
app.listen(3030, () => {
  console.log('server started on port 3030');
});

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

npm run start

and access the application by visiting 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()
      };
    })
  );
});

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

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

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

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

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

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

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 in this repository.

Thanks for reading!

Want to learn all ES6+ features in detail including let and const, promises, various promise methods, array and object destructuring, arrow functions, async/await, import and export and a whole lot more from scratch?

Check out my Mastering Modern JavaScript book. This book covers all the pre-requisites for learning React and helps you to become better at JavaScript and React.

Check out free preview contents of the book here.

Also, you can check out my free Introduction to React Router course to learn React Router from scratch.

Want to stay up to date with regular content regarding JavaScript, React, Node.js? Follow me on LinkedIn.

Did you find this article valuable?

Support Yogesh Chavan by becoming a sponsor. Any amount is appreciated!