Guest User

Untitled

a guest
May 22nd, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. const fs = require('fs');
  2.  
  3. // Get CLI params
  4. const sqlJsonPath = process.argv[2];
  5. const outputType = process.argv[3];
  6. const outputFilePath = process.argv[4];
  7.  
  8. // Show generic CLI syntax error with usage
  9. const showCommandError = () => {
  10. console.log(`
  11. Command syntex incorrect!
  12.  
  13. Usage example;
  14.  
  15. node parsqlres.js data.json --json [or --csv] output.json
  16. `);
  17. };
  18.  
  19. // Proceed only if SQL JSON file is provided
  20. if (sqlJsonPath) {
  21. // Extract data file contents
  22. const sqlJson = JSON.parse(fs.readFileSync(sqlJsonPath));
  23. const sqlAxis = sqlJson.axis;
  24. const sqlData = sqlJson.data;
  25.  
  26. // Process data based on output type
  27. switch (outputType) {
  28. // If output type is JSON
  29. case '--json':
  30. // Iterate over data array and create
  31. // JSON object for each array item
  32. const parsedJson = sqlData.map((dataItem) => {
  33. const record = {};
  34.  
  35. // Create key-value pairs from column
  36. // and data
  37. sqlAxis.forEach((column, index) => {
  38. record[column] = dataItem[index];
  39. });
  40.  
  41. // return map object
  42. return record;
  43. });
  44.  
  45. // Write JSON array to output file path
  46. // `null` is replacer function
  47. // `2` is for spaces to use for indentation in file
  48. // `utf-8` is for file encoding
  49. fs.writeFileSync(outputFilePath, JSON.stringify(parsedJson, null, 2), 'utf-8');
  50. break;
  51.  
  52. // If output type is CSV
  53. case '--csv':
  54. // Open stream to write file with `a` flag for appending contents
  55. const csvWriter = fs.createWriteStream(outputFilePath, { flags: 'a' });
  56.  
  57. // Write column names enclosed in quotes and separated by comma
  58. csvWriter.write(sqlAxis.map(column => `"${column}"`).join(',') + '\n');
  59.  
  60. // Iterate over each data item
  61. sqlData.forEach((dataItem) => {
  62. // Write data values enclosed in quotes and separated by comma
  63. csvWriter.write(dataItem.map(column => `"${column}"`).join(',') + '\n');
  64. });
  65.  
  66. // Close stream
  67. csvWriter.end();
  68. break;
  69.  
  70. default:
  71. showCommandError();
  72. break;
  73. }
  74. } else {
  75. showCommandError();
  76. }
Add Comment
Please, Sign In to add comment