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).
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
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 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
Add a new start
script inside package.json
file
"scripts": {
"start": "nodemon index.js"
}
Your package.json
file will look like this now
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 bylodash
which will execute the provided functioncount
number of times. Lodash library is optimized for performance so instead of using an arraymap
method to generate for example 1000 records, we’re usinglodash
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 oftimes
method will be an array of objects with the generated values. - Then we’re sending that result using
send
method of response object usingres.send
- Then at the end, we’re starting the
Express.js
server on port3030
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 http://localhost:3030/address?count=10
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.
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.
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()
};
})
);
});
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.
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.
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.
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.
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.
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.
Top comments (6)
Pls update this article, the creator of
faker.js
had put a critical issue to this library and nobody uses it now.Thanks for pointing that out @hongphuc5497 . I have updated the introduction section of this tutorial to mention the updated library.
If you need to create reusable objects with faker, checkout node-factory. It helps a lot with mocks and tests while reducing code duplication.
npmjs.com/package/node-factory
Thanks for the suggestion. It really looks nice way to reduce code duplication 👍
Cool guide easy to follow faker is such a useful package.
Thanks... yeah, Don't know How I lived without faker for so long.. it's simple and extremely useful library