code icon Code

Generate Fake Data

Generate realistic fake data for testing and demos

Source Code

import fs from "fs";
import path from "path";
import { faker } from "@faker-js/faker";

const [schemaJson, countStr, outputPath, locale = "en"] = process.argv.slice(2);

if (!schemaJson || !countStr || !outputPath) {
  console.error("Usage: schema count outputPath [locale]");
  process.exit(1);
}

/**
 * Get faker method by path (e.g., "person.fullName" -> faker.person.fullName)
 */
function getFakerMethod(path) {
  const parts = path.split(".");
  let current = faker;

  for (const part of parts) {
    if (current && typeof current === "object" && part in current) {
      current = current[part];
    } else {
      return null;
    }
  }

  return typeof current === "function" ? current.bind(faker) : null;
}

try {
  console.log(`Generating fake data...`);

  // Set locale
  faker.locale = locale;

  let schema;
  try {
    schema = JSON.parse(schemaJson);
  } catch {
    console.error("Invalid schema JSON:", schemaJson);
    process.exit(1);
  }

  const count = parseInt(countStr, 10);
  if (isNaN(count) || count < 1) {
    console.error("Count must be a positive integer");
    process.exit(1);
  }

  console.log(`  Schema fields: ${Object.keys(schema).join(", ")}`);
  console.log(`  Count: ${count}`);
  console.log(`  Locale: ${locale}`);

  // Validate schema methods exist
  const methods = {};
  for (const [field, fakerPath] of Object.entries(schema)) {
    const method = getFakerMethod(fakerPath);
    if (!method) {
      console.error(`Unknown faker method: ${fakerPath}`);
      console.error(`Available methods: person.fullName, internet.email, phone.number, etc.`);
      process.exit(1);
    }
    methods[field] = method;
  }

  // Generate data
  const records = [];
  for (let i = 0; i < count; i++) {
    const record = {};
    for (const [field, method] of Object.entries(methods)) {
      record[field] = method();
    }
    records.push(record);
  }

  // Ensure output directory exists
  const dir = path.dirname(outputPath);
  if (dir && dir !== ".") {
    fs.mkdirSync(dir, { recursive: true });
  }

  fs.writeFileSync(outputPath, JSON.stringify(records, null, 2));

  console.log(`\nāœ“ Generated fake data`);
  console.log(`  Records: ${records.length}`);
  console.log(`  Fields: ${Object.keys(schema).join(", ")}`);
  console.log(`  Written to: ${outputPath}`);

  // Show sample
  if (records.length > 0) {
    console.log(`  Sample: ${JSON.stringify(records[0])}`);
  }

  console.log(
    JSON.stringify({
      success: true,
      outputPath,
      count: records.length,
      fields: Object.keys(schema),
      locale,
    })
  );
} catch (error) {
  console.error("Error:", error.message);
  process.exit(1);
}