The faker.js tutorial
last modified July 7, 2020
The faker.js tutorial shows how to generate fake data in JavaScript with faker.js library.
faker.js
faker.js is a JavaScript library for generating fake data. Fake data is useful when building and testing our application. The faker.js can generate fake data for various areas, including address, commerce, company, date, finance, image, random, or name.
In this tutorial we work with faker.js in a Node application.
Setting up faker.js
First, we install faker.js.
$ node -v v11.5.0
We use Node version 11.5.0.
$ npm init -y
We initiate a new Node application.
$ npm i faker
We install faker.js module with nmp i faker
.
Faking names
In the first example, we fake data related to user names.
const faker = require('faker'); let firstName = faker.name.firstName(); let lastName = faker.name.lastName(); let jobTitle = faker.name.jobTitle(); let prefix = faker.name.prefix(); let suffix = faker.name.suffix(); let jobArea = faker.name.jobArea(); let phone = faker.phone.phoneNumber(); console.log(`Employee: ${prefix} ${firstName} ${lastName} ${suffix}`); console.log(`Job title: ${jobTitle}`); console.log(`Job area: ${jobArea}`); console.log(`Phone: ${phone}`);
The example creates a random first name, last name, job title, name prefix and suffix, job area, and phone number.
const faker = require('faker');
We require the faker module.
let firstName = faker.name.firstName();
We generate a fake first name with the firstName()
function.
The function is located in the name object.
$ node names.js Employee: Mrs. Vernice Abernathy III Job title: Customer Data Associate Job area: Program Phone: 1-516-716-9832
This is a sample output.
Faking dates
In the second example, we generate fake dates.
const faker = require('faker'); let futureDate = faker.date.future(); let recentDate = faker.date.recent(); let weekday = faker.date.weekday(); console.log(futureDate); console.log(recentDate); console.log(weekday);
The example picks up a future and recent date and some weekday.
$ node dates.js 2019-04-13T19:09:43.672Z 2019-01-06T12:28:29.089Z Saturday
This is a sample output.
Faking random values
The faker allows to generate random values, such as integers, uuids, or words.
const faker = require('faker'); let number = faker.random.number(); console.log(number); let uuid = faker.random.uuid(); console.log(uuid); let word = faker.random.word(); console.log(word); let words = faker.random.words(6); console.log(words);
The example generates random number, uuid, word, and a group of six words.
$ node random_values.js 630 1470356a-1197-4955-b3c1-30302fd1db10 Facilitator dot-com connect Practical Checking Account Mandatory real-time
This is a sample output.
Faking locale data
The faker supports localized data to some extent. Note that the locales are finished to various levels.
const faker = require('faker/locale/ru'); let firstName = faker.name.firstName(); let lastName = faker.name.lastName(); console.log(`Pаботник: ${firstName} ${lastName}`); let month = faker.date.month(); let recentDate = faker.date.recent(); let rectentDate = faker.date.weekday(); console.log(month); console.log(recentDate); console.log(rectentDate);
The example generates fake data in Russian language.
$ node locale_faker.js Pаботник: Антон Васильева май 2019-01-06T19:24:01.283Z Пятница
This is a sample output.
Serving fake data with JSON Server
In the next example, we generate JSON data and write it to file. The file is served by JSON Server.
$ npm i g json-server
We install json-server
module.
const faker = require('faker'); const fs = require('fs') function generateUsers() { let users = [] for (let id=1; id <= 100; id++) { let firstName = faker.name.firstName(); let lastName = faker.name.lastName(); let email = faker.internet.email(); users.push({ "id": id, "first_name": firstName, "last_name": lastName, "email": email }); } return { "data": users } } let dataObj = generateUsers(); fs.writeFileSync('data.json', JSON.stringify(dataObj, null, '\t'));
The example generates one-hundred users and writes them to a data.json
file.
$ json-server --watch data.json --port 3004
We start the JSON Server. The server serves data from the generated JSON file.
$ curl localhost:3004/data/3/ { "id": 3, "first_name": "Sheila", "last_name": "Bayer", "email": "Moshe.Walsh32@yahoo.com" }
We retrieve the user with Id 3 with the curl
tool.
We show how to generate a HTTP GET request in JavaScript with the Node request
module.
$ npm i request
We install the module.
const request = require('request'); request('http://localhost:3004/data?_start=4&_end=8', (err, resp, body) => { if (err) { console.error('request failed'); console.error(err); } else { console.log(body); } });
The program fetches data from the JSON Server, beginning with index 4 (exclusive) and ending with index 8 (inclusive).
$ node get_data.js [ { "id": 5, "first_name": "Cheyanne", "last_name": "Ernser", "email": "Amber.Spinka62@yahoo.com" }, { "id": 6, "first_name": "Jeff", "last_name": "Bogisich", "email": "Bettie.Ritchie60@hotmail.com" }, { "id": 7, "first_name": "Simone", "last_name": "Zemlak", "email": "Dorris49@gmail.com" }, { "id": 8, "first_name": "Demond", "last_name": "Barrows", "email": "Nestor81@yahoo.com" } ]
This is a sample output.
Faker CLI
The faker-cli
is a Node module, which is a wrapper over the faker.js
.
It allows to generate fake data from a command line tool.
$ npm install -g faker-cli
We install the faker-cli
module.
$ faker-cli -d future "2019-07-22T06:37:19.032Z" $ faker-cli -d recent "2019-01-06T21:46:50.788Z" $ faker-cli -n firstName "Tevin" $ faker-cli -n lastName "Sawayn"
We generate some fake data with the faker-cli
program.
In this tutorial, we have used faker.js to generate fake data in JavaScript.
List all JavaScript tutorials.