csv.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const json2csv = require('json2csv')
  2. const fs = require('fs-extra')
  3. const path = require('path')
  4. const log = require('../util/log')
  5. module.exports.format = function (data, options) {
  6. var processedData = data.map(el => {
  7. var row = {}
  8. // Iterate over the columns and add each item to the new row.
  9. for (var key in options.columns) {
  10. row[key] = options.columns[key](el)
  11. }
  12. return row
  13. })
  14. const csv = json2csv({ data: processedData })
  15. if (options.program) {
  16. // If reporting output is defined, ignore console log here.
  17. if (options.program.output === undefined) {
  18. log.raw(csv)
  19. }
  20. } else {
  21. log.raw(csv)
  22. }
  23. return csv
  24. }
  25. module.exports.finalReport = async function (reports, program) {
  26. if (program.output === undefined) {
  27. return
  28. }
  29. // Ensure the output directory exists.
  30. fs.ensureDirSync(program.output)
  31. // Write each report to the disk
  32. for (var report of reports) {
  33. var outPath = path.join(program.output, report.name + '.csv')
  34. log.action('saving', outPath)
  35. fs.writeFileSync(outPath, report.contents, 'utf8')
  36. }
  37. }