1. #!/usr/bin/env node
  2. const fs = require('fs');
  3. const path = require('path');
  4. const { program } = require('commander');
  5. program
  6. .version('1.0.0')
  7. .description('Truncate data in datasets for temporary use.')
  8. .requiredOption('-i, --input <file>', 'Path to the input dataset file (CSV or JSON).')
  9. .option('-o, --output <file>', 'Path to the output dataset file.')
  10. .option('-n, --numRows <number>', 'Number of rows to keep.', parseInt)
  11. .parse(process.argv);
  12. const options = program.opts();
  13. function truncateDataset(inputFile, outputFile, numRows) {
  14. try {
  15. let data;
  16. let fileType = path.extname(inputFile).toLowerCase();
  17. if (fileType === '.csv') {
  18. data = fs.readFileSync(inputFile, 'utf8').split('\n');
  19. data = data.slice(0, numRows); // Truncate CSV
  20. } else if (fileType === '.json') {
  21. data = JSON.parse(fs.readFileSync(inputFile, 'utf8'));
  22. if (Array.isArray(data)) {
  23. data = data.slice(0, numRows); // Truncate JSON array
  24. } else {
  25. console.error("JSON file does not contain an array.");
  26. process.exit(1);
  27. }
  28. } else {
  29. console.error('Unsupported file type. Only CSV and JSON are supported.');
  30. process.exit(1);
  31. }
  32. if (outputFile) {
  33. if (fileType === '.csv') {
  34. fs.writeFileSync(outputFile, data.join('\n'));
  35. } else if (fileType === '.json') {
  36. fs.writeFileSync(outputFile, JSON.stringify(data, null, 2)); //Pretty print JSON
  37. }
  38. } else {
  39. console.log(JSON.stringify(data, null, 2)); //Output to console if no output file is specified
  40. }
  41. } catch (err) {
  42. console.error('Error:', err.message);
  43. process.exit(1);
  44. }
  45. }
  46. truncateDataset(options.input, options.output, options.numRows);

Add your comment