Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs');
- // Get CLI params
- const sqlJsonPath = process.argv[2];
- const outputType = process.argv[3];
- const outputFilePath = process.argv[4];
- // Show generic CLI syntax error with usage
- const showCommandError = () => {
- console.log(`
- Command syntex incorrect!
- Usage example;
- node parsqlres.js data.json --json [or --csv] output.json
- `);
- };
- // Proceed only if SQL JSON file is provided
- if (sqlJsonPath) {
- // Extract data file contents
- const sqlJson = JSON.parse(fs.readFileSync(sqlJsonPath));
- const sqlAxis = sqlJson.axis;
- const sqlData = sqlJson.data;
- // Process data based on output type
- switch (outputType) {
- // If output type is JSON
- case '--json':
- // Iterate over data array and create
- // JSON object for each array item
- const parsedJson = sqlData.map((dataItem) => {
- const record = {};
- // Create key-value pairs from column
- // and data
- sqlAxis.forEach((column, index) => {
- record[column] = dataItem[index];
- });
- // return map object
- return record;
- });
- // Write JSON array to output file path
- // `null` is replacer function
- // `2` is for spaces to use for indentation in file
- // `utf-8` is for file encoding
- fs.writeFileSync(outputFilePath, JSON.stringify(parsedJson, null, 2), 'utf-8');
- break;
- // If output type is CSV
- case '--csv':
- // Open stream to write file with `a` flag for appending contents
- const csvWriter = fs.createWriteStream(outputFilePath, { flags: 'a' });
- // Write column names enclosed in quotes and separated by comma
- csvWriter.write(sqlAxis.map(column => `"${column}"`).join(',') + '\n');
- // Iterate over each data item
- sqlData.forEach((dataItem) => {
- // Write data values enclosed in quotes and separated by comma
- csvWriter.write(dataItem.map(column => `"${column}"`).join(',') + '\n');
- });
- // Close stream
- csvWriter.end();
- break;
- default:
- showCommandError();
- break;
- }
- } else {
- showCommandError();
- }
Add Comment
Please, Sign In to add comment