csv.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // Default columns to an empty object
  7. options.colums = options.columns || {}
  8. // Check if the array is empty. If so, return an empty string.
  9. if (data instanceof Array && data.length === 0) {
  10. return ''
  11. }
  12. // If we didn't get a data object, make it an array for ease of use.
  13. if (!(data instanceof Array) && typeof data === 'object') {
  14. data = [data]
  15. }
  16. // Do some preprocessing to find the columns.
  17. if ((!options.columns || Object.keys(options.colums).length === 0) && data.length > 0) {
  18. // Extract the fields from the first object.
  19. options.columns = Object.keys(data[0])
  20. log.verbose('assigning csv columns to', options.columns)
  21. }
  22. function processRow (el) {
  23. var row = {}
  24. // Iterate over the columns and add each item to the new row.
  25. for (var key of options.columns) {
  26. if (typeof options.columns[key] === 'function') {
  27. row[key] = options.columns[key](el)
  28. } else {
  29. row[key] = el[key]
  30. }
  31. }
  32. return row
  33. }
  34. var processedData = data.map(processRow)
  35. const csv = json2csv({ data: processedData, fieldNames: Object.keys(data[0]) })
  36. // Print the output if required.
  37. if (!options.program || options.program.output === undefined) {
  38. log.raw(csv)
  39. }
  40. return csv
  41. }
  42. module.exports.finalReport = async function (reports, program) {
  43. if (program.output === undefined) {
  44. return
  45. }
  46. // Ensure the output directory exists.
  47. fs.ensureDirSync(program.output)
  48. // Write each report to the disk
  49. for (var report of reports) {
  50. var outPath = path.join(program.output, report.name + '.csv')
  51. log.action('saving', outPath)
  52. if (program.output === '-') {
  53. console.log(report.contents)
  54. } else {
  55. fs.writeFileSync(outPath, report.contents, 'utf8')
  56. }
  57. }
  58. }