Faker.js : A developer’s time saving library

Faker.js is a JavaScript library that allows you to generate fake data for various purposes, such as testing, development, or demonstration. Faker.js can create realistic and diverse data for different domains, such as address, commerce, company, date, finance, image, random, or name. You can use Faker.js in both browser and Node.js environments, and it supports multiple languages and locales. Faker.js is easy to install and use, and it offers a rich and flexible API for customizing the data generation.

How to setup Faker.js to use

Dependencies CLI:

Add following dependencies to your application

npm install - save json-server
npm install @faker-js/faker --save

Steps:

  • create a server folder
  • create database.json file inside server folder
  • create generate.json file inside server folder
  • type sample script to generate dummy data in generate.json. Here I am generating data for product.
    • Script
import { faker } from '@faker-js/faker'
var database = { products: []};
for (var i = 1; i<= 300; i++) {
    database.products.push({
        id: i,
        name: faker.commerce.productName(),
        description: faker.lorem.sentences(),
        price: faker.commerce.price(),
        imageUrl: "https://source.unsplash.com/1600x900/?product",
        quantity: faker.datatype.number()
    });
}
console.log(JSON.stringify(database));
  • type below script in package.json file to run script
    • Script
"scripts":{
    .
    .
    "generate": "node ./server/generate.js > ./server/database.json",
    "server": "json-server --watch ./server/database.json --port 3000"
    .
    .
}
  • Now run npm run generate command to generate dummy data
  • if you get any error like module type error add { "type" : "module" } in package.json file
  • After successfully generating dummy data you can open database.json file to see json data
  • Now run npm run server to start server to get fake rest api to get data

API List

  • [GET] /products – for getting the products
  • [GET] /products/ – for getting a single product by id
  • [POST] /products – for creating a new product
  • [PUT] /products/ – for updating a product by id
  • [PATCH] /products/ – for partially updating a product by id
  • [DELETE] /products/ – for deleting a product by id

References:

Leave a Reply