Project: Build a Node.js CLI Test-Data Generator
Testers need data: users to register, orders to place, CSV files to upload. Typing it by hand is slow, copying production data is risky, and random data that changes on every run makes failures impossible to reproduce. In this project you will build qa-data, a real Node.js command-line tool that generates realistic Indian test users as JSON or CSV, the same data every time for a given seed, and writes it to the terminal or a file. You will use modules, util.parseArgs, the file system, error handling, exit codes, package.json “bin”, and finally test the CLI with node:test. Every command on this page was really run.
📖 What You’ll Learn: how to design a command-line tool, seeded pseudo-random numbers for repeatable data, generating realistic users with unique emails, converting to JSON and correctly escaped CSV, parsing arguments and flags with util.parseArgs, help text, validation and error messages on stderr, exit codes, writing output files, making the tool installable with the package.json bin field and npm link, and testing a CLI by running it as a child process.
📋 Requirements and Project Layout
| # | Requirement |
|---|---|
| R1 | qa-data prints 5 users as JSON by default |
| R2 | --count / -n sets how many (1–10000); invalid values give a clear error |
| R3 | --format csv outputs CSV with a header row and correct quoting |
| R4 | The same --seed always produces exactly the same data |
| R5 | Emails are unique; phone numbers look like valid Indian mobiles (+91, starting 6–9) |
| R6 | --out writes a file, creating folders as needed |
| R7 | Errors go to stderr with exit code 1; --help shows usage |
📁 Project structure
qa-data/
├── package.json "bin" makes the qa-data command
├── qa-data.js the CLI: arguments, output, errors
├── src/
│ ├── random.js seeded random numbers
│ ├── generate.js builds user objects (pure)
│ └── format.js JSON and CSV conversion (pure)
└── test/
└── cli.test.js node:test tests
As in the to-do project, the logic (src/) is pure and testable, and the entry file only deals with the outside world: arguments, the terminal and files.
🎲 Step 1: Repeatable Random Data
Math.random() cannot be seeded, so a failing test that used random data cannot be reproduced. A small seeded generator fixes that: the same seed gives the same numbers on every machine:
📄 src/random.js
// Seeded pseudo-random numbers (mulberry32): the same seed always gives the same sequence
export function createRandom(seed) {
let state = seed >>> 0;
const next = () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296; // 0 <= n < 1
};
return {
next,
int: (min, max) => min + Math.floor(next() * (max - min + 1)),
pick: (list) => list[Math.floor(next() * list.length)],
};
}
📄 try-random.js
import { createRandom } from "./src/random.js";
const a = createRandom(42), b = createRandom(42), c = createRandom(7);
console.log([1, 2, 3].map(() => a.int(1, 100)));
console.log([1, 2, 3].map(() => b.int(1, 100)), "same seed, same numbers");
console.log([1, 2, 3].map(() => c.int(1, 100)), "different seed");
console.log(createRandom(1).pick(["chromium", "firefox", "webkit"]));
⌨️ Terminal
node try-random.js
🖥️ Output
[ 61, 45, 86 ]
[ 61, 45, 86 ] same seed, same numbers
[ 2, 7, 98 ] different seed
firefox
📌 Note: This kind of generator is fine for test data but not for anything security-related; use crypto.randomUUID() or crypto.getRandomValues() for tokens and passwords.
👤 Step 2: Generate Users and Format Them
The generator picks names, cities and roles from lists, builds an email and a phone number, and guarantees unique emails with a Set (Module 7):
📄 src/generate.js
import { createRandom } from "./random.js";
const FIRST = ["Asha", "Ravi", "Meera", "Arjun", "Priya", "Kabir", "Neha", "Vikram", "Sara", "Rohan"];
const LAST = ["Rao", "Sharma", "Iyer", "Khan", "Patel", "Das", "Nair", "Singh", "Gupta", "Mehta"];
const CITIES = ["Pune", "Bengaluru", "Mumbai", "Delhi", "Chennai", "Hyderabad", "Kolkata", "Jaipur"];
const ROLES = ["viewer", "tester", "lead", "admin"];
export function generateUsers({ count = 5, seed = 42, domain = "test.sqatools.in" } = {}) {
if (!Number.isInteger(count) || count < 1 || count > 10_000) {
throw new RangeError("count must be a whole number from 1 to 10000");
}
const rnd = createRandom(seed);
const usedEmails = new Set();
return Array.from({ length: count }, (_, i) => {
const first = rnd.pick(FIRST);
const last = rnd.pick(LAST);
let email = `${first}.${last}`.toLowerCase() + `@${domain}`;
if (usedEmails.has(email)) email = email.replace("@", `${i + 1}@`); // keep emails unique
usedEmails.add(email);
return {
id: i + 1,
name: `${first} ${last}`,
email,
phone: `+91${rnd.int(6, 9)}${String(rnd.int(0, 999_999_999)).padStart(9, "0")}`,
city: rnd.pick(CITIES),
age: rnd.int(18, 60),
role: rnd.pick(ROLES),
};
});
}
CSV looks simple until a value contains a comma or a quote. The formatter quotes such values and doubles inner quotes, as the CSV standard requires:
📄 src/format.js
// CSV needs quoting when a value contains a comma, a quote or a line break
const csvCell = (value) => {
const text = String(value);
return /[",\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
};
export function toCsv(rows) {
if (rows.length === 0) return "";
const headers = Object.keys(rows[0]);
return [headers.join(","), ...rows.map((r) => headers.map((h) => csvCell(r[h])).join(","))].join("\n") + "\n";
}
export function toJson(rows) {
return JSON.stringify(rows, null, 2) + "\n";
}
📄 try-csv.js
import { toCsv } from "./src/format.js";
console.log(toCsv([
{ id: 1, name: "Asha Rao", note: "likes Playwright" },
{ id: 2, name: "Rao, Ravi", note: 'said "hello"' },
]));
⌨️ Terminal
node try-csv.js
🖥️ Output
id,name,note
1,Asha Rao,likes Playwright
2,"Rao, Ravi","said ""hello"""
⌨️ Step 3: The Command-Line Interface
Node.js has a built-in argument parser, util.parseArgs, so no package is needed. The entry file reads options, validates them, prints errors to stderr and sets a non-zero exit code on failure, which is how shells and CI systems know a command failed:
📄 qa-data.js
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { generateUsers } from "./src/generate.js";
import { toCsv, toJson } from "./src/format.js";
const HELP = `Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help`;
function fail(message) {
console.error(`qa-data: ${message}\nRun "qa-data --help" for usage.`);
process.exitCode = 1; // non-zero exit code = failure (CI notices)
}
async function main(argv) {
let values;
try {
({ values } = parseArgs({
args: argv,
options: {
count: { type: "string", short: "n", default: "5" },
format: { type: "string", short: "f", default: "json" },
seed: { type: "string", short: "s", default: "42" },
out: { type: "string", short: "o" },
help: { type: "boolean", short: "h", default: false },
},
}));
} catch (error) {
return fail(error.message); // unknown option, missing value...
}
if (values.help) return console.log(HELP);
if (!["json", "csv"].includes(values.format)) return fail(`unknown format "${values.format}" (use json or csv)`);
let users;
try {
users = generateUsers({ count: Number(values.count), seed: Number(values.seed) });
} catch (error) {
return fail(error.message);
}
const text = values.format === "csv" ? toCsv(users) : toJson(users);
if (!values.out) return process.stdout.write(text);
await mkdir(dirname(values.out), { recursive: true });
await writeFile(values.out, text);
console.log(`Wrote ${users.length} users to ${values.out} (${values.format})`);
}
await main(process.argv.slice(2));
📄 package.json
{
"name": "qa-data",
"version": "1.0.0",
"type": "module",
"bin": { "qa-data": "./qa-data.js" },
"scripts": { "test": "node --test" }
}
- The first line,
#!/usr/bin/env node(a “shebang”), lets macOS and Linux run the file as a command; npm creates the right launcher on Windows. process.exitCode = 1marks failure but lets pending output finish, which is safer thanprocess.exit(1).- Data goes to stdout and messages to stderr, so
qa-data > users.jsonnever writes an error message into the data file.
▶️ Step 4: Run It
Default run: 5 users as JSON (here 2, to keep the page short):
📄 qa-data.js
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { generateUsers } from "./src/generate.js";
import { toCsv, toJson } from "./src/format.js";
const HELP = `Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help`;
function fail(message) {
console.error(`qa-data: ${message}\nRun "qa-data --help" for usage.`);
process.exitCode = 1; // non-zero exit code = failure (CI notices)
}
async function main(argv) {
let values;
try {
({ values } = parseArgs({
args: argv,
options: {
count: { type: "string", short: "n", default: "5" },
format: { type: "string", short: "f", default: "json" },
seed: { type: "string", short: "s", default: "42" },
out: { type: "string", short: "o" },
help: { type: "boolean", short: "h", default: false },
},
}));
} catch (error) {
return fail(error.message); // unknown option, missing value...
}
if (values.help) return console.log(HELP);
if (!["json", "csv"].includes(values.format)) return fail(`unknown format "${values.format}" (use json or csv)`);
let users;
try {
users = generateUsers({ count: Number(values.count), seed: Number(values.seed) });
} catch (error) {
return fail(error.message);
}
const text = values.format === "csv" ? toCsv(users) : toJson(users);
if (!values.out) return process.stdout.write(text);
await mkdir(dirname(values.out), { recursive: true });
await writeFile(values.out, text);
console.log(`Wrote ${users.length} users to ${values.out} (${values.format})`);
}
await main(process.argv.slice(2));
⌨️ Terminal
node qa-data.js --count 2
🖥️ Output
[
{
"id": 1,
"name": "Neha Patel",
"email": "neha.patel@test.sqatools.in",
"phone": "+919669734041",
"city": "Bengaluru",
"age": 40,
"role": "tester"
},
{
"id": 2,
"name": "Neha Gupta",
"email": "neha.gupta@test.sqatools.in",
"phone": "+917249923734",
"city": "Jaipur",
"age": 50,
"role": "tester"
}
]
CSV output, and the same seed producing the same people (R4):
📄 qa-data.js
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { generateUsers } from "./src/generate.js";
import { toCsv, toJson } from "./src/format.js";
const HELP = `Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help`;
function fail(message) {
console.error(`qa-data: ${message}\nRun "qa-data --help" for usage.`);
process.exitCode = 1; // non-zero exit code = failure (CI notices)
}
async function main(argv) {
let values;
try {
({ values } = parseArgs({
args: argv,
options: {
count: { type: "string", short: "n", default: "5" },
format: { type: "string", short: "f", default: "json" },
seed: { type: "string", short: "s", default: "42" },
out: { type: "string", short: "o" },
help: { type: "boolean", short: "h", default: false },
},
}));
} catch (error) {
return fail(error.message); // unknown option, missing value...
}
if (values.help) return console.log(HELP);
if (!["json", "csv"].includes(values.format)) return fail(`unknown format "${values.format}" (use json or csv)`);
let users;
try {
users = generateUsers({ count: Number(values.count), seed: Number(values.seed) });
} catch (error) {
return fail(error.message);
}
const text = values.format === "csv" ? toCsv(users) : toJson(users);
if (!values.out) return process.stdout.write(text);
await mkdir(dirname(values.out), { recursive: true });
await writeFile(values.out, text);
console.log(`Wrote ${users.length} users to ${values.out} (${values.format})`);
}
await main(process.argv.slice(2));
⌨️ Terminal
node qa-data.js -n 4 --format csv
🖥️ Output
id,name,email,phone,city,age,role
1,Neha Patel,neha.patel@test.sqatools.in,+919669734041,Bengaluru,40,tester
2,Neha Gupta,neha.gupta@test.sqatools.in,+917249923734,Jaipur,50,tester
3,Ravi Das,ravi.das@test.sqatools.in,+918610620898,Pune,38,admin
4,Asha Das,asha.das@test.sqatools.in,+916266955986,Pune,25,admin
📄 qa-data.js
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { generateUsers } from "./src/generate.js";
import { toCsv, toJson } from "./src/format.js";
const HELP = `Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help`;
function fail(message) {
console.error(`qa-data: ${message}\nRun "qa-data --help" for usage.`);
process.exitCode = 1; // non-zero exit code = failure (CI notices)
}
async function main(argv) {
let values;
try {
({ values } = parseArgs({
args: argv,
options: {
count: { type: "string", short: "n", default: "5" },
format: { type: "string", short: "f", default: "json" },
seed: { type: "string", short: "s", default: "42" },
out: { type: "string", short: "o" },
help: { type: "boolean", short: "h", default: false },
},
}));
} catch (error) {
return fail(error.message); // unknown option, missing value...
}
if (values.help) return console.log(HELP);
if (!["json", "csv"].includes(values.format)) return fail(`unknown format "${values.format}" (use json or csv)`);
let users;
try {
users = generateUsers({ count: Number(values.count), seed: Number(values.seed) });
} catch (error) {
return fail(error.message);
}
const text = values.format === "csv" ? toCsv(users) : toJson(users);
if (!values.out) return process.stdout.write(text);
await mkdir(dirname(values.out), { recursive: true });
await writeFile(values.out, text);
console.log(`Wrote ${users.length} users to ${values.out} (${values.format})`);
}
await main(process.argv.slice(2));
⌨️ Terminal
node qa-data.js -n 4 -f csv --seed 42
🖥️ Output
id,name,email,phone,city,age,role
1,Neha Patel,neha.patel@test.sqatools.in,+919669734041,Bengaluru,40,tester
2,Neha Gupta,neha.gupta@test.sqatools.in,+917249923734,Jaipur,50,tester
3,Ravi Das,ravi.das@test.sqatools.in,+918610620898,Pune,38,admin
4,Asha Das,asha.das@test.sqatools.in,+916266955986,Pune,25,admin
A different seed gives different, but again repeatable, data:
📄 qa-data.js
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { generateUsers } from "./src/generate.js";
import { toCsv, toJson } from "./src/format.js";
const HELP = `Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help`;
function fail(message) {
console.error(`qa-data: ${message}\nRun "qa-data --help" for usage.`);
process.exitCode = 1; // non-zero exit code = failure (CI notices)
}
async function main(argv) {
let values;
try {
({ values } = parseArgs({
args: argv,
options: {
count: { type: "string", short: "n", default: "5" },
format: { type: "string", short: "f", default: "json" },
seed: { type: "string", short: "s", default: "42" },
out: { type: "string", short: "o" },
help: { type: "boolean", short: "h", default: false },
},
}));
} catch (error) {
return fail(error.message); // unknown option, missing value...
}
if (values.help) return console.log(HELP);
if (!["json", "csv"].includes(values.format)) return fail(`unknown format "${values.format}" (use json or csv)`);
let users;
try {
users = generateUsers({ count: Number(values.count), seed: Number(values.seed) });
} catch (error) {
return fail(error.message);
}
const text = values.format === "csv" ? toCsv(users) : toJson(users);
if (!values.out) return process.stdout.write(text);
await mkdir(dirname(values.out), { recursive: true });
await writeFile(values.out, text);
console.log(`Wrote ${users.length} users to ${values.out} (${values.format})`);
}
await main(process.argv.slice(2));
⌨️ Terminal
node qa-data.js -n 3 -f csv -s 2026
🖥️ Output
id,name,email,phone,city,age,role
1,Priya Khan,priya.khan@test.sqatools.in,+918618475218,Bengaluru,27,lead
2,Sara Iyer,sara.iyer@test.sqatools.in,+916066587695,Chennai,34,viewer
3,Ravi Khan,ravi.khan@test.sqatools.in,+917920866378,Chennai,18,viewer
Help and errors
📄 qa-data.js
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { generateUsers } from "./src/generate.js";
import { toCsv, toJson } from "./src/format.js";
const HELP = `Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help`;
function fail(message) {
console.error(`qa-data: ${message}\nRun "qa-data --help" for usage.`);
process.exitCode = 1; // non-zero exit code = failure (CI notices)
}
async function main(argv) {
let values;
try {
({ values } = parseArgs({
args: argv,
options: {
count: { type: "string", short: "n", default: "5" },
format: { type: "string", short: "f", default: "json" },
seed: { type: "string", short: "s", default: "42" },
out: { type: "string", short: "o" },
help: { type: "boolean", short: "h", default: false },
},
}));
} catch (error) {
return fail(error.message); // unknown option, missing value...
}
if (values.help) return console.log(HELP);
if (!["json", "csv"].includes(values.format)) return fail(`unknown format "${values.format}" (use json or csv)`);
let users;
try {
users = generateUsers({ count: Number(values.count), seed: Number(values.seed) });
} catch (error) {
return fail(error.message);
}
const text = values.format === "csv" ? toCsv(users) : toJson(users);
if (!values.out) return process.stdout.write(text);
await mkdir(dirname(values.out), { recursive: true });
await writeFile(values.out, text);
console.log(`Wrote ${users.length} users to ${values.out} (${values.format})`);
}
await main(process.argv.slice(2));
⌨️ Terminal
node qa-data.js --help
🖥️ Output
Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help
📄 qa-data.js
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { generateUsers } from "./src/generate.js";
import { toCsv, toJson } from "./src/format.js";
const HELP = `Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help`;
function fail(message) {
console.error(`qa-data: ${message}\nRun "qa-data --help" for usage.`);
process.exitCode = 1; // non-zero exit code = failure (CI notices)
}
async function main(argv) {
let values;
try {
({ values } = parseArgs({
args: argv,
options: {
count: { type: "string", short: "n", default: "5" },
format: { type: "string", short: "f", default: "json" },
seed: { type: "string", short: "s", default: "42" },
out: { type: "string", short: "o" },
help: { type: "boolean", short: "h", default: false },
},
}));
} catch (error) {
return fail(error.message); // unknown option, missing value...
}
if (values.help) return console.log(HELP);
if (!["json", "csv"].includes(values.format)) return fail(`unknown format "${values.format}" (use json or csv)`);
let users;
try {
users = generateUsers({ count: Number(values.count), seed: Number(values.seed) });
} catch (error) {
return fail(error.message);
}
const text = values.format === "csv" ? toCsv(users) : toJson(users);
if (!values.out) return process.stdout.write(text);
await mkdir(dirname(values.out), { recursive: true });
await writeFile(values.out, text);
console.log(`Wrote ${users.length} users to ${values.out} (${values.format})`);
}
await main(process.argv.slice(2));
⌨️ Terminal
node qa-data.js --count 0
🖥️ Output
qa-data: count must be a whole number from 1 to 10000
Run "qa-data --help" for usage.
📄 qa-data.js
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { generateUsers } from "./src/generate.js";
import { toCsv, toJson } from "./src/format.js";
const HELP = `Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help`;
function fail(message) {
console.error(`qa-data: ${message}\nRun "qa-data --help" for usage.`);
process.exitCode = 1; // non-zero exit code = failure (CI notices)
}
async function main(argv) {
let values;
try {
({ values } = parseArgs({
args: argv,
options: {
count: { type: "string", short: "n", default: "5" },
format: { type: "string", short: "f", default: "json" },
seed: { type: "string", short: "s", default: "42" },
out: { type: "string", short: "o" },
help: { type: "boolean", short: "h", default: false },
},
}));
} catch (error) {
return fail(error.message); // unknown option, missing value...
}
if (values.help) return console.log(HELP);
if (!["json", "csv"].includes(values.format)) return fail(`unknown format "${values.format}" (use json or csv)`);
let users;
try {
users = generateUsers({ count: Number(values.count), seed: Number(values.seed) });
} catch (error) {
return fail(error.message);
}
const text = values.format === "csv" ? toCsv(users) : toJson(users);
if (!values.out) return process.stdout.write(text);
await mkdir(dirname(values.out), { recursive: true });
await writeFile(values.out, text);
console.log(`Wrote ${users.length} users to ${values.out} (${values.format})`);
}
await main(process.argv.slice(2));
⌨️ Terminal
node qa-data.js --format xml
🖥️ Output
qa-data: unknown format "xml" (use json or csv)
Run "qa-data --help" for usage.
📄 qa-data.js
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { generateUsers } from "./src/generate.js";
import { toCsv, toJson } from "./src/format.js";
const HELP = `Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help`;
function fail(message) {
console.error(`qa-data: ${message}\nRun "qa-data --help" for usage.`);
process.exitCode = 1; // non-zero exit code = failure (CI notices)
}
async function main(argv) {
let values;
try {
({ values } = parseArgs({
args: argv,
options: {
count: { type: "string", short: "n", default: "5" },
format: { type: "string", short: "f", default: "json" },
seed: { type: "string", short: "s", default: "42" },
out: { type: "string", short: "o" },
help: { type: "boolean", short: "h", default: false },
},
}));
} catch (error) {
return fail(error.message); // unknown option, missing value...
}
if (values.help) return console.log(HELP);
if (!["json", "csv"].includes(values.format)) return fail(`unknown format "${values.format}" (use json or csv)`);
let users;
try {
users = generateUsers({ count: Number(values.count), seed: Number(values.seed) });
} catch (error) {
return fail(error.message);
}
const text = values.format === "csv" ? toCsv(users) : toJson(users);
if (!values.out) return process.stdout.write(text);
await mkdir(dirname(values.out), { recursive: true });
await writeFile(values.out, text);
console.log(`Wrote ${users.length} users to ${values.out} (${values.format})`);
}
await main(process.argv.slice(2));
⌨️ Terminal
node qa-data.js --colour red
🖥️ Output
qa-data: Unknown option '--colour'
Run "qa-data --help" for usage.
Each error run prints one clear message on stderr and ends with exit code 1, so a script or CI job that calls qa-data stops instead of continuing with bad data. The tests in step 6 check both the message and the exit code.
Writing a file
📄 qa-data.js
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { generateUsers } from "./src/generate.js";
import { toCsv, toJson } from "./src/format.js";
const HELP = `Usage: qa-data [options]
Generate realistic, repeatable test users.
Options:
-n, --count <number> how many users (1-10000, default 5)
-f, --format <type> json or csv (default json)
-s, --seed <number> seed for repeatable data (default 42)
-o, --out <file> write to a file instead of the terminal
-h, --help show this help`;
function fail(message) {
console.error(`qa-data: ${message}\nRun "qa-data --help" for usage.`);
process.exitCode = 1; // non-zero exit code = failure (CI notices)
}
async function main(argv) {
let values;
try {
({ values } = parseArgs({
args: argv,
options: {
count: { type: "string", short: "n", default: "5" },
format: { type: "string", short: "f", default: "json" },
seed: { type: "string", short: "s", default: "42" },
out: { type: "string", short: "o" },
help: { type: "boolean", short: "h", default: false },
},
}));
} catch (error) {
return fail(error.message); // unknown option, missing value...
}
if (values.help) return console.log(HELP);
if (!["json", "csv"].includes(values.format)) return fail(`unknown format "${values.format}" (use json or csv)`);
let users;
try {
users = generateUsers({ count: Number(values.count), seed: Number(values.seed) });
} catch (error) {
return fail(error.message);
}
const text = values.format === "csv" ? toCsv(users) : toJson(users);
if (!values.out) return process.stdout.write(text);
await mkdir(dirname(values.out), { recursive: true });
await writeFile(values.out, text);
console.log(`Wrote ${users.length} users to ${values.out} (${values.format})`);
}
await main(process.argv.slice(2));
// --- check what was written (not part of the CLI) ---
const { readFile } = await import("node:fs/promises");
console.log((await readFile("test-data/users.csv", "utf8")).split("\n").slice(0, 3).join("\n"));
⌨️ Terminal
node qa-data.js -n 100 -f csv -o test-data/users.csv
🖥️ Output
Wrote 100 users to test-data/users.csv (csv)
id,name,email,phone,city,age,role
1,Neha Patel,neha.patel@test.sqatools.in,+919669734041,Bengaluru,40,tester
2,Neha Gupta,neha.gupta@test.sqatools.in,+917249923734,Jaipur,50,tester
📦 Step 5: Make It an Installable Command
The "bin" field in package.json maps a command name to the entry file. Inside the project folder, npm link installs it as a global command for your machine; teammates can run it without installing with npx:
⌨️ Terminal
npm link
qa-data --count 3 --format csv
# in another project that has qa-data as a dev dependency
npx qa-data -n 50 -o test-data/users.json
To share it, push the folder to Git (teammates run npm install and npx qa-data), or publish it to npm with npm publish after choosing a unique package name.
🧪 Step 6: Test the CLI
Two levels of tests: the pure functions directly, and the real command as a child process, checking its output, stderr and exit code exactly as a user or CI would see them:
📄 cli.test.js
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { generateUsers } from "./src/generate.js";
import { toCsv } from "./src/format.js";
const runCli = (...args) => spawnSync(process.execPath, ["qa-data.js", ...args], { encoding: "utf8" });
describe("generateUsers", () => {
test("same seed gives the same users", () => {
assert.deepEqual(generateUsers({ count: 20, seed: 9 }), generateUsers({ count: 20, seed: 9 }));
});
test("emails are unique and phones look valid", () => {
const users = generateUsers({ count: 500, seed: 1 });
assert.equal(new Set(users.map((u) => u.email)).size, 500);
assert.ok(users.every((u) => /^\+91[6-9]\d{9}$/.test(u.phone)));
assert.ok(users.every((u) => u.age >= 18 && u.age <= 60));
});
test("rejects counts outside 1-10000", () => {
for (const count of [0, -1, 10_001, 2.5, NaN]) assert.throws(() => generateUsers({ count }), RangeError);
});
});
describe("toCsv", () => {
test("quotes commas and doubles quotes", () => {
assert.equal(toCsv([{ a: "x,y", b: 'say "hi"' }]), 'a,b\n"x,y","say ""hi"""\n');
});
});
describe("qa-data command", () => {
test("prints JSON by default with exit code 0", () => {
const r = runCli("-n", "3");
assert.equal(r.status, 0);
assert.equal(JSON.parse(r.stdout).length, 3);
});
test("writes CSV with a header row", () => {
const lines = runCli("-n", "2", "-f", "csv").stdout.trim().split("\n");
assert.equal(lines[0], "id,name,email,phone,city,age,role");
assert.equal(lines.length, 3);
});
test("invalid input goes to stderr with exit code 1", () => {
for (const args of [["--count", "0"], ["--format", "xml"], ["--bogus"]]) {
const r = runCli(...args);
assert.equal(r.status, 1, args.join(" "));
assert.equal(r.stdout, "");
assert.match(r.stderr, /^qa-data: /);
}
});
});
⌨️ Terminal
node --test
🖥️ Output
▶ generateUsers
✔ same seed gives the same users (2.9456ms)
✔ emails are unique and phones look valid (3.7691ms)
✔ rejects counts outside 1-10000 (0.7843ms)
✔ generateUsers (9.7474ms)
▶ toCsv
✔ quotes commas and doubles quotes (0.4136ms)
✔ toCsv (0.6425ms)
▶ qa-data command
✔ prints JSON by default with exit code 0 (135.3968ms)
✔ writes CSV with a header row (133.8552ms)
✔ invalid input goes to stderr with exit code 1 (347.7568ms)
✔ qa-data command (617.694ms)
ℹ tests 7
ℹ suites 3
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 806.6982
🧪 Tester Scenario: Using the Data in Playwright Tests
Generate the data once (or in a setup step) and drive data-driven tests from it. Because the seed is fixed, a failure for “user 17” is reproducible on every machine:
⌨️ Terminal
npx qa-data -n 20 -s 2026 -o test-data/users.json
📄 tests/register.spec.js (Playwright)
import { test, expect } from "@playwright/test";
import users from "../test-data/users.json" with { type: "json" };
for (const user of users.slice(0, 5)) {
test(`registers ${user.email}`, async ({ page }) => {
await page.goto("/register");
await page.getByLabel("Full name").fill(user.name);
await page.getByLabel("Email").fill(user.email);
await page.getByLabel("Mobile").fill(user.phone);
await page.getByRole("button", { name: "Create account" }).click();
await expect(page.getByRole("status")).toContainText(user.name.split(" ")[0]);
});
}
- Never use real customer data in tests; generated data avoids privacy problems.
- Use a dedicated test domain for emails (here test.sqatools.in) so no real person receives mail.
- Add options such as
--type ordersor--localeas your needs grow; keep each generator a pure, tested function.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Add a --domain option so users can choose the email domain. Which three places in the code change?
Show answer
The parseArgs options (domain: { type: "string", default: "test.sqatools.in" }), the call generateUsers({ ..., domain: values.domain }) (generateUsers already accepts it), and the HELP text. Add a test that checks every email ends with the chosen domain.
Q2. Write toMarkdown(rows) that turns rows into a Markdown table.
Show answer
📄 practice2.js
const toMarkdown = (rows) => {
const h = Object.keys(rows[0]);
return [`| ${h.join(" | ")} |`, `| ${h.map(() => "---").join(" | ")} |`, ...rows.map((r) => `| ${h.map((k) => r[k]).join(" | ")} |`)].join("\n");
};
console.log(toMarkdown([{ id: 1, name: "Asha" }, { id: 2, name: "Ravi" }]));🖥️ Output
| id | name |
| --- | --- |
| 1 | Asha |
| 2 | Ravi |Q3. Use parseArgs to read --env staging --verbose into an object.
Show answer
📄 practice3.mjs
import { parseArgs } from "node:util";
const { values } = parseArgs({
args: ["--env", "staging", "--verbose"],
options: { env: { type: "string", default: "local" }, verbose: { type: "boolean", default: false } },
});
console.log(values);🖥️ Output
[Object: null prototype] { env: 'staging', verbose: true }Q4. Write a generator for order ids like ORD-2026-00042 using the seeded random module, and show it is repeatable.
Show answer
📄 practice4.js
import { createRandom } from "./src/random.js";
const orderIds = (n, seed) => { const r = createRandom(seed); return Array.from({ length: n }, () => `ORD-2026-${String(r.int(1, 99999)).padStart(5, "0")}`); };
console.log(orderIds(3, 5));
console.log(orderIds(3, 5));🖥️ Output
[ 'ORD-2026-68977', 'ORD-2026-77274', 'ORD-2026-21977' ]
[ 'ORD-2026-68977', 'ORD-2026-77274', 'ORD-2026-21977' ]Q5. Why does the CLI print errors with console.error instead of console.log?
Show answer
console.error writes to stderr. When output is redirected (qa-data > users.json) or piped into another program, only stdout goes there, so error text never corrupts the data, and the user still sees the message in the terminal. Together with a non-zero exit code, it lets scripts and CI detect failure reliably.
Q6. A teammate says “the test failed with user Vikram Singh, but I cannot reproduce it”. What two pieces of information from the run do you need?
Show answer
The seed and the count (and the tool version). With the same seed and count, qa-data generates exactly the same users, so the failing case can be regenerated and re-run. That is why test reports should log the seed used.
🧠 MCQ Quiz: Project: Node.js CLI
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which built-in Node.js function parses command-line options?Answer: util.parseArgs. No package needed for most CLIs.
- Where are the raw command-line arguments?Answer: process.argv. The first two entries are node and the script path.
- Why use a seeded random generator for test data?Answer: The same seed reproduces the same data. Reproducible failures.
- What exit code signals failure to a shell or CI?Answer: Any non-zero code, usually 1. 0 means success.
- Where should error messages go?Answer: stderr (console.error). Keeps data output clean.
- How do you write a CSV value containing a comma?Answer: Wrap it in double quotes. Inner quotes are doubled.
- What does the “bin” field in package.json do?Answer: Maps a command name to a script file. npm link or npx can then run it.
- What does
#!/usr/bin/env nodeat the top of a file do?Answer: Lets Unix systems run the file directly with Node.js. It is called a shebang. - How can a test check a CLI’s exit code and stderr?Answer: Run it with child_process.spawnSync and inspect status and stderr. It tests the real command.
- Why use a test email domain such as test.sqatools.in?Answer: So no real person receives emails from tests. Generated data protects privacy.
💼 Interview Questions and Answers
Q1. How do you manage test data in an automation framework?
Generate it rather than copying production data: builders and factories in code for unit and UI tests, seeded generators or fixtures for larger sets, and API calls to create data on the system under test with clean-up afterwards. Keep data reproducible (fixed seeds, logged values), isolated per test (unique emails or ids), and free of personal information.
Q2. How would you make a flaky test caused by random data reproducible?
Replace Math.random with a seeded generator, choose the seed per run (or per test), and print it in the test output and report. When a failure appears, re-run with the same seed to get the same data. Property-based testing libraries such as fast-check do this automatically and also shrink the failing input to the smallest example.
Q3. What makes a good command-line tool?
Clear –help text, sensible defaults, validation with specific error messages, data on stdout and messages on stderr, meaningful exit codes, no interactive prompts when run in CI, idempotent file writing (creating folders as needed), and tests that run the real command. Pure core logic in separate modules keeps it maintainable.
Q4. Why test the CLI as a child process as well as unit testing its functions?
Unit tests prove the generators and formatters are correct. Running the real command proves the wiring: argument parsing, defaults, output format, stderr, exit codes and file writing, which is what users and CI depend on. Both are fast enough to run on every commit.
❓ Frequently Asked Questions
🤔 Should I use a library such as commander or yargs?
For small tools util.parseArgs is enough. Libraries help with sub-commands, generated help, and advanced validation in bigger CLIs.
🤔 Is there a library for fake data?
Yes: @faker-js/faker generates names, addresses, companies and more in many locales and supports seeding with faker.seed(). Building your own generator, as here, teaches how such tools work and has no dependency.
🤔 How do I add colours to terminal output?
Node.js has util.styleText (for example styleText("green", "PASS")). Respect the NO_COLOR environment variable so output stays clean in logs.
🤔 Can the CLI run on Windows, macOS and Linux?
Yes. Use node:path for paths, avoid shell-specific commands, and let npm create the platform-specific launcher from the bin field.
🏁 Summary
- Design the CLI from testable requirements; keep generators and formatters as pure modules.
- Use a seeded random generator so the same seed reproduces the same test data.
- Parse options with util.parseArgs, show –help, validate input, write errors to stderr and set exit code 1.
- Write files with fs/promises (creating folders), and expose the command with package.json “bin”, npm link and npx.
- Test pure functions directly and the real command via spawnSync; feed the generated data into Playwright tests.
Next, continue with Lesson 74: Project: API Checker.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in