Creating Node.js CLI Tool That Generates Type Specific Data

Waleed JavedWaleed Javed
4 min read

We will walk through the process of creating a Node.js Command-Line Interface (CLI) tool that generates random data using the faker library. Additionally, we'll enhance the output using the chalk library to add color and style to the command-line interface. This tool allows users to specify the type of data they want and saves the generated data to a JSON file.

Prerequisites

Make sure you have Node.js and npm installed on your machine. You'll also need to install the faker and chalk libraries:

npm install faker chalk

Step 1: Setting up the Project

Create a new directory for your project and navigate into it:

mkdir random-data-generator
cd random-data-generator

Step 2: Writing the CLI Script

Create a new file, e.g., generateData.js, and copy the following script into it:

#!/usr/bin/env node
//above line alows to utilize node on user machine

const fs = require('fs');
const faker = require('faker');
const yargs = require('yargs');
const chalk = require('chalk');

Step 3: Configuring Command-Line Options

Use the yargs library to configure command-line options, making it easy for users to specify the amount and type of data they want.

// ... (copy the rest of the script from the previous code snippet)

// Configure command-line options
const options = yargs
  .usage('<amount of data to generate> <type>')
  .demandCommand(2, 'Please provide both amount and type of data')
  .argv;

// Extract command-line arguments
const amount = parseInt(options._[0]);
const type = options._[1];

Step 4: Generating Random Data

Implement a function that generates random data based on the user's input. Use the faker library to create realistic data entries.

// ... (copy the rest of the script from the previous code snippet)

// Generate random data based on type
function generateData(amount, type) {
  const data = [];
  for (let i = 0; i < amount; i++) {
    let entry;

    //Switch to Add multiple casses in future
    switch (type)
    {
      case 'user':
        entry = {
          name: faker.name.findName(),
          email: faker.internet.email(),
          address: faker.address.streetAddress(),
        };
        break;
      // Add more cases for other types if needed

        default:
        console.error(chalk.red('Invalid data type. Supported types: user'));
        process.exit(1);
    }

    //append data array
    data.push(entry);
  }

  // return generated data 
  return data;
}


// Generate data by calling the generateData function
const generatedData = generateData(amount, type);

Step 5: Writing Data to JSON File

Write the generated data to a JSON file, making it easy for users to consume and share the data.

// ... (copy the rest of the script from the previous code snippet)

// Write data to a JSON file that is saved at root/mockData directory
const fileName = `./mockData/generated_data_${type}_${amount}.json`;
fs.writeFileSync(fileName, JSON.stringify(generatedData, null, 2));

Step 6: Adding Color to Output

Enhance the command-line output by adding color and style using the chalk library. Provide visual feedback for success and error messages.

// ... (copy the rest of the script from the previous code snippet)

//Chalk Library allows us to make fonts and bg colorful
console.log(chalk.green(`Generated data successfully and saved to ${fileName}`));

Step 7: Making the Script Executable

Make the script executable by updating its permissions:

chmod +x generateData.js

Step 8: Running the CLI Tool

Demonstrate how to run the CLI tool and generate random data with examples:

npx ./generateData.js 10 user

NOTE: "./generateData" , is relative path, when using from another dir/file, reference path accordingly.

Conclusion

In this tutorial, we've created a Node.js CLI tool to generate random data with faker and added colorful output using chalk. This tool provides a simple yet effective way to create custom datasets for various applications.

Feel free to expand on this project by adding more data types, refining the output format, or incorporating additional features based on your specific use case.

  • Remember to replace placeholders and customize the content based on your preferences and additional information you'd like to include.


I hope it was insightful and helped you get familiar with how Command-line-interface tools work. Post likes/comments and share in your circles.

p.s Let's connect.
You can follow me on Hashnode, and I also share content on these platforms:

0
Subscribe to my newsletter

Read articles from Waleed Javed directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Waleed Javed
Waleed Javed

Building Enterprise Softwares🚀 | Sharing insights on Linkedin/in/Waleed-javed