csv-faker-generator 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Manoj Kengudelu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # CSV Faker Generator
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/csv-faker-generator.svg)](https://www.npmjs.com/package/csv-faker-generator)
4
+ [![npm downloads](https://img.shields.io/npm/dm/csv-faker-generator.svg)](https://www.npmjs.com/package/csv-faker-generator)
5
+ [![CI](https://github.com/manojkken/csv-faker-generator/actions/workflows/ci.yml/badge.svg)](https://github.com/manojkken/csv-faker-generator/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
7
+
3
8
  Generate CSV files with realistic fake data using customizable headers and data types. Perfect for testing, prototyping, and development.
4
9
 
5
10
  ## Features
@@ -8,6 +13,7 @@ Generate CSV files with realistic fake data using customizable headers and data
8
13
  - **Advanced data generation**: Alphanumeric strings, pick from custom values, formula-based calculated fields
9
14
  - **Flexible number formatting**: Control decimal precision and ranges
10
15
  - **Custom delimiters**: Support for comma, semicolon, tab, pipe
16
+ - **Multiple output formats**: CSV, JSON arrays, and newline-delimited JSON
11
17
  - **Simple CLI interface**: Generate CSV files from command line
12
18
  - **Programmatic API**: Use in Node.js/TypeScript projects
13
19
  - **Full TypeScript support**: Complete type definitions included
@@ -28,6 +34,10 @@ npx csv-faker -c id:uuid,name:name,email:email -r 100 -o users.csv
28
34
 
29
35
  # With custom delimiter
30
36
  npx csv-faker -c id:uuid,name:name,email:email --delimiter ";" -r 50 -o contacts.csv
37
+
38
+ # JSON and NDJSON (also inferred from .json and .ndjson output extensions)
39
+ npx csv-faker -c id:uuid,name:name,email:email -r 100 -o users.json
40
+ npx csv-faker -c id:uuid,name:name,email:email -r 100 -f ndjson -o users.data
31
41
  ```
32
42
 
33
43
  ### Programmatic Usage
@@ -46,6 +56,20 @@ await generateCSV({
46
56
  });
47
57
  ```
48
58
 
59
+ Set `format` to `'json'` for an array of row objects or `'ndjson'` for one row object per line. It defaults to `'csv'` in programmatic usage.
60
+
61
+ ```typescript
62
+ await generateCSV({
63
+ columns: [
64
+ { header: 'id', type: 'uuid' },
65
+ { header: 'active', type: 'boolean' },
66
+ ],
67
+ rows: 100,
68
+ output: 'users.json',
69
+ format: 'json',
70
+ });
71
+ ```
72
+
49
73
  ## Advanced Features
50
74
 
51
75
  ### 1. Alphanumeric Type
@@ -197,6 +221,7 @@ await generateCSV({
197
221
  - `--columns, -c` - Column definitions (format: `header:type,header:type,...`)
198
222
  - `--rows, -r` - Number of rows to generate (default: 10)
199
223
  - `--output, -o` - Output file path (default: output.csv)
224
+ - `--format, -f` - Output format: `csv`, `json`, or `ndjson` (default: inferred from `.json` / `.ndjson` extension, otherwise `csv`)
200
225
  - `--delimiter, -d` - Field delimiter (default: `,`) [options: `,` `;` `|` `\t`]
201
226
  - `--help, -h` - Show help message
202
227
 
@@ -278,6 +303,7 @@ interface GenerateOptions {
278
303
  columns: ColumnDefinition[];
279
304
  rows: number;
280
305
  output: string;
306
+ format?: 'csv' | 'json' | 'ndjson'; // Default: 'csv'
281
307
  delimiter?: string; // Default: ','
282
308
  }
283
309
 
package/dist/cli.js CHANGED
@@ -1,7 +1,41 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
3
36
  Object.defineProperty(exports, "__esModule", { value: true });
4
37
  const index_1 = require("./index");
38
+ const path = __importStar(require("node:path"));
5
39
  const args = process.argv.slice(2);
6
40
  function showHelp() {
7
41
  console.log(`
@@ -14,6 +48,7 @@ Options:
14
48
  --columns, -c Column definitions (format: header:type,header:type,...)
15
49
  --rows, -r Number of rows to generate (default: 10)
16
50
  --output, -o Output file path (default: output.csv)
51
+ --format, -f Output format: csv, json, or ndjson (default: inferred from output extension)
17
52
  --delimiter, -d Field delimiter (default: ,) [options: , ; | \\t]
18
53
  --help, -h Show this help message
19
54
 
@@ -31,12 +66,15 @@ Examples:
31
66
  csv-faker -c userId:uuid,firstName:firstName,lastName:lastName,email:email,address:address -r 50
32
67
  csv-faker --columns "id:uuid,company:company,city:city" --rows 20 --output companies.csv
33
68
  csv-faker -c id:uuid,name:name,email:email --delimiter ";" -r 50 -o contacts.csv
69
+ csv-faker -c id:uuid,name:name -r 50 -o users.json
70
+ csv-faker -c id:uuid,name:name -r 50 -f ndjson -o users.data
34
71
  `);
35
72
  }
36
73
  function parseArgs() {
37
74
  let columnsStr = '';
38
75
  let rows = 10;
39
76
  let output = 'output.csv';
77
+ let format;
40
78
  let delimiter = ',';
41
79
  for (let i = 0; i < args.length; i++) {
42
80
  const arg = args[i];
@@ -57,6 +95,13 @@ function parseArgs() {
57
95
  else if (arg === '--output' || arg === '-o') {
58
96
  output = args[++i];
59
97
  }
98
+ else if (arg === '--format' || arg === '-f') {
99
+ const value = args[++i];
100
+ if (value !== 'csv' && value !== 'json' && value !== 'ndjson') {
101
+ throw new Error(`Invalid format: ${value}. Expected csv, json, or ndjson`);
102
+ }
103
+ format = value;
104
+ }
60
105
  else if (arg === '--delimiter' || arg === '-d') {
61
106
  delimiter = args[++i];
62
107
  // Handle common escape sequences
@@ -71,7 +116,13 @@ function parseArgs() {
71
116
  process.exit(1);
72
117
  }
73
118
  const columns = columnsStr.split(',').map(index_1.parseColumnString);
74
- return { columns, rows, output, delimiter };
119
+ if (!format) {
120
+ const extension = path.extname(output).slice(1).toLowerCase();
121
+ if (extension === 'json' || extension === 'ndjson') {
122
+ format = extension;
123
+ }
124
+ }
125
+ return { columns, rows, output, format, delimiter };
75
126
  }
76
127
  async function main() {
77
128
  try {
package/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ export interface GenerateOptions {
14
14
  columns: ColumnDefinition[];
15
15
  rows: number;
16
16
  output: string;
17
+ format?: 'csv' | 'json' | 'ndjson';
17
18
  delimiter?: string;
18
19
  }
19
20
  export declare function generateCSV(options: GenerateOptions): Promise<void>;
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ exports.generateCSV = generateCSV;
4
4
  exports.parseColumnString = parseColumnString;
5
5
  const faker_1 = require("@faker-js/faker");
6
6
  const csv_writer_1 = require("csv-writer");
7
+ const promises_1 = require("node:fs/promises");
7
8
  function generateValue(column, row) {
8
9
  const { type, min, max, length, uppercase, values, decimals } = column;
9
10
  switch (type) {
@@ -36,9 +37,9 @@ function generateValue(column, row) {
36
37
  case 'jobTitle':
37
38
  return faker_1.faker.person.jobTitle();
38
39
  case 'number': {
39
- const num = faker_1.faker.number.int({ min: min || 1, max: max || 1000 });
40
+ const num = faker_1.faker.number.int({ min: min ?? 1, max: max ?? 1000 });
40
41
  if (decimals !== undefined) {
41
- const float = faker_1.faker.number.float({ min: min || 1, max: max || 1000, fractionDigits: decimals });
42
+ const float = faker_1.faker.number.float({ min: min ?? 1, max: max ?? 1000, fractionDigits: decimals });
42
43
  return parseFloat(float.toFixed(decimals));
43
44
  }
44
45
  return num;
@@ -86,15 +87,7 @@ function generateValue(column, row) {
86
87
  }
87
88
  }
88
89
  async function generateCSV(options) {
89
- const { columns, rows, output, delimiter = ',' } = options;
90
- const csvWriter = (0, csv_writer_1.createObjectCsvWriter)({
91
- path: output,
92
- header: columns.map((col) => ({
93
- id: col.header,
94
- title: col.header,
95
- })),
96
- fieldDelimiter: delimiter,
97
- });
90
+ const { columns, rows, output, format = 'csv', delimiter = ',' } = options;
98
91
  const records = [];
99
92
  for (let i = 0; i < rows; i++) {
100
93
  const record = {};
@@ -112,7 +105,24 @@ async function generateCSV(options) {
112
105
  }
113
106
  records.push(record);
114
107
  }
115
- await csvWriter.writeRecords(records);
108
+ if (format === 'json') {
109
+ await (0, promises_1.writeFile)(output, `${JSON.stringify(records, null, 2)}\n`);
110
+ }
111
+ else if (format === 'ndjson') {
112
+ const content = records.map((record) => JSON.stringify(record)).join('\n');
113
+ await (0, promises_1.writeFile)(output, content ? `${content}\n` : '');
114
+ }
115
+ else {
116
+ const csvWriter = (0, csv_writer_1.createObjectCsvWriter)({
117
+ path: output,
118
+ header: columns.map((col) => ({
119
+ id: col.header,
120
+ title: col.header,
121
+ })),
122
+ fieldDelimiter: delimiter,
123
+ });
124
+ await csvWriter.writeRecords(records);
125
+ }
116
126
  console.log(`✓ Generated ${rows} rows in ${output}`);
117
127
  }
118
128
  function parseColumnString(columnStr) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "csv-faker-generator",
3
- "version": "2.0.0",
4
- "description": "Generate CSV files with fake data: 27+ data types, alphanumeric strings, pick from custom values, formula fields, decimal precision, custom delimiters. Perfect for testing and prototyping.",
3
+ "version": "2.1.0",
4
+ "description": "Generate CSV, JSON, or NDJSON files with fake data: 27+ data types, alphanumeric strings, pick from custom values, formula fields, decimal precision, custom delimiters. Perfect for testing and prototyping.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "bin": {
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "repository": {
11
11
  "type": "git",
12
- "url": "https://github.com/manojkken/csv-faker-generator.git"
12
+ "url": "git+https://github.com/manojkken/csv-faker-generator.git"
13
13
  },
14
14
  "homepage": "https://github.com/manojkken/csv-faker-generator#readme",
15
15
  "bugs": {
@@ -18,7 +18,7 @@
18
18
  "scripts": {
19
19
  "build": "tsc",
20
20
  "prepare": "npm run build",
21
- "test": "node dist/example.js"
21
+ "test": "npm run build && node --test test/index.test.js"
22
22
  },
23
23
  "keywords": [
24
24
  "csv",
@@ -37,13 +37,19 @@
37
37
  "test-data",
38
38
  "prototyping",
39
39
  "iban",
40
- "banking"
40
+ "banking",
41
+ "json",
42
+ "ndjson",
43
+ "fixtures"
41
44
  ],
42
45
  "author": "Manoj Kengudelu",
43
46
  "license": "MIT",
44
47
  "files": [
45
48
  "dist",
46
- "README.md"
49
+ "!dist/example.*",
50
+ "!dist/test-advanced.*",
51
+ "README.md",
52
+ "LICENSE"
47
53
  ],
48
54
  "dependencies": {
49
55
  "@faker-js/faker": "^10.1.0",
@@ -53,4 +59,4 @@
53
59
  "@types/node": "^24.10.1",
54
60
  "typescript": "^5.9.3"
55
61
  }
56
- }
62
+ }
package/dist/example.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};
package/dist/example.js DELETED
@@ -1,55 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const index_1 = require("./index");
4
- async function runExamples() {
5
- console.log('Running CSV Faker Generator examples...\n');
6
- console.log('Example 1: Generating user data...');
7
- await (0, index_1.generateCSV)({
8
- columns: [
9
- { header: 'id', type: 'uuid' },
10
- { header: 'name', type: 'name' },
11
- { header: 'email', type: 'email' },
12
- { header: 'address', type: 'address' },
13
- { header: 'phone', type: 'phone' },
14
- ],
15
- rows: 10,
16
- output: 'example-users.csv',
17
- });
18
- console.log('\nExample 2: Generating employee data with age range...');
19
- await (0, index_1.generateCSV)({
20
- columns: [
21
- { header: 'employeeId', type: 'uuid' },
22
- { header: 'firstName', type: 'firstName' },
23
- { header: 'lastName', type: 'lastName' },
24
- { header: 'email', type: 'email' },
25
- { header: 'age', type: 'number', min: 22, max: 65 },
26
- { header: 'jobTitle', type: 'jobTitle' },
27
- { header: 'company', type: 'company' },
28
- { header: 'salary', type: 'number', min: 40000, max: 150000 },
29
- ],
30
- rows: 15,
31
- output: 'example-employees.csv',
32
- });
33
- console.log('\nExample 3: Generating company data...');
34
- await (0, index_1.generateCSV)({
35
- columns: [
36
- { header: 'companyId', type: 'uuid' },
37
- { header: 'companyName', type: 'company' },
38
- { header: 'city', type: 'city' },
39
- { header: 'country', type: 'country' },
40
- { header: 'website', type: 'url' },
41
- { header: 'verified', type: 'boolean' },
42
- ],
43
- rows: 8,
44
- output: 'example-companies.csv',
45
- });
46
- console.log('\n✓ All examples completed successfully!');
47
- console.log('\nGenerated files:');
48
- console.log(' - example-users.csv (10 rows)');
49
- console.log(' - example-employees.csv (15 rows)');
50
- console.log(' - example-companies.csv (8 rows)');
51
- }
52
- runExamples().catch((error) => {
53
- console.error('Error running examples:', error);
54
- process.exit(1);
55
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,110 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const index_1 = require("./index");
4
- async function testAdvancedFeatures() {
5
- console.log('Testing Advanced Features...\n');
6
- // Test 1: Alphanumeric with length and uppercase
7
- console.log('Test 1: Alphanumeric type with custom length and uppercase...');
8
- await (0, index_1.generateCSV)({
9
- columns: [
10
- { header: 'product_code', type: 'alphanumeric', length: 10, uppercase: true },
11
- { header: 'sku', type: 'alphanumeric', length: 15 },
12
- { header: 'name', type: 'name' },
13
- ],
14
- rows: 5,
15
- output: 'test-alphanumeric.csv',
16
- });
17
- // Test 2: Pick type for enum values
18
- console.log('\nTest 2: Pick type for predefined values...');
19
- await (0, index_1.generateCSV)({
20
- columns: [
21
- { header: 'product', type: 'name' },
22
- { header: 'tax_rate', type: 'pick', values: [0, 7, 19] },
23
- { header: 'status', type: 'pick', values: ['active', 'pending', 'inactive'] },
24
- { header: 'unit', type: 'pick', values: ['g', 'kg', 'Stück', 'Meter'] },
25
- ],
26
- rows: 5,
27
- output: 'test-pick.csv',
28
- });
29
- // Test 3: Formula fields (calculated values)
30
- console.log('\nTest 3: Formula type for calculated fields...');
31
- await (0, index_1.generateCSV)({
32
- columns: [
33
- { header: 'product', type: 'company' },
34
- { header: 'netto', type: 'number', min: 10, max: 200, decimals: 2 },
35
- { header: 'tax', type: 'pick', values: [0, 7, 19] },
36
- {
37
- header: 'brutto',
38
- type: 'formula',
39
- formula: (row) => {
40
- const netto = row.netto;
41
- const tax = row.tax;
42
- return parseFloat((netto * (1 + tax / 100)).toFixed(2));
43
- },
44
- },
45
- ],
46
- rows: 5,
47
- output: 'test-formula.csv',
48
- });
49
- // Test 4: Custom delimiter (semicolon)
50
- console.log('\nTest 4: Custom delimiter (semicolon)...');
51
- await (0, index_1.generateCSV)({
52
- columns: [
53
- { header: 'id', type: 'uuid' },
54
- { header: 'name', type: 'name' },
55
- { header: 'email', type: 'email' },
56
- ],
57
- rows: 5,
58
- delimiter: ';',
59
- output: 'test-semicolon.csv',
60
- });
61
- // Test 5: Number with decimal precision
62
- console.log('\nTest 5: Number type with decimal precision...');
63
- await (0, index_1.generateCSV)({
64
- columns: [
65
- { header: 'price', type: 'number', min: 10, max: 200, decimals: 2 },
66
- { header: 'weight', type: 'number', min: 0.1, max: 99.9, decimals: 1 },
67
- { header: 'quantity', type: 'number', min: 1, max: 1000, decimals: 0 },
68
- ],
69
- rows: 5,
70
- output: 'test-decimals.csv',
71
- });
72
- // Test 6: Complete E-commerce Article Example
73
- console.log('\nTest 6: Complete e-commerce article example (the dogfooding use case)...');
74
- await (0, index_1.generateCSV)({
75
- columns: [
76
- { header: 'Artikelnummer*', type: 'alphanumeric', length: 15 },
77
- { header: 'Bezeichnung*', type: 'company' },
78
- { header: 'Beschreibung', type: 'company' },
79
- { header: 'Verkaufspreis netto in €', type: 'number', min: 10, max: 200, decimals: 2 },
80
- { header: 'Steuersatz', type: 'pick', values: [0, 7, 19] },
81
- {
82
- header: 'Verkaufspreis brutto in €',
83
- type: 'formula',
84
- formula: (row) => {
85
- const netto = row['Verkaufspreis netto in €'];
86
- const tax = row['Steuersatz'];
87
- return parseFloat((netto * (1 + tax / 100)).toFixed(2));
88
- },
89
- },
90
- { header: 'Einkaufspreis netto in €', type: 'number', min: 5, max: 100, decimals: 2 },
91
- { header: 'Einheit', type: 'pick', values: ['Stück', 'kg', 'g', 'Meter', 'Liter'] },
92
- { header: 'Bestand', type: 'number', min: 0, max: 1000, decimals: 0 },
93
- { header: 'Kategorie', type: 'pick', values: ['Electronics', 'Food', 'Clothing', 'Books'] },
94
- ],
95
- rows: 10,
96
- output: 'test-articles-complete.csv',
97
- });
98
- console.log('\n✓ All advanced feature tests completed successfully!');
99
- console.log('\nGenerated files:');
100
- console.log(' - test-alphanumeric.csv (alphanumeric with length/uppercase)');
101
- console.log(' - test-pick.csv (pick from predefined values)');
102
- console.log(' - test-formula.csv (calculated fields)');
103
- console.log(' - test-semicolon.csv (custom delimiter)');
104
- console.log(' - test-decimals.csv (decimal precision)');
105
- console.log(' - test-articles-complete.csv (complete e-commerce example)');
106
- }
107
- testAdvancedFeatures().catch((error) => {
108
- console.error('Error running advanced tests:', error);
109
- process.exit(1);
110
- });