json.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. const fs = require('fs-extra')
  2. const path = require('path')
  3. const log = require('../util/log')
  4. module.exports.format = function (data, options) {
  5. function convertRow (el) {
  6. // No Columns defined, just return raw object.
  7. if (!options.columns || Object.keys(options.columns).length === 0) {
  8. return el
  9. }
  10. var row = {}
  11. // Iterate over the columns and add each item to the new row.
  12. for (var key in options.columns) {
  13. row[key] = options.columns[key](el)
  14. }
  15. return row
  16. }
  17. var processedData
  18. if (data instanceof Array) {
  19. processedData = data.map(convertRow)
  20. } else {
  21. processedData = convertRow(data)
  22. }
  23. // Strigify the output, using 2 space indent.
  24. var output = JSON.stringify(processedData, null, 2)
  25. if (options.program) {
  26. // If reporting output is defined, ignore console log here.
  27. if (options.program.output === undefined) {
  28. log.raw(output)
  29. } else {
  30. return processedData
  31. }
  32. } else {
  33. log.raw(output)
  34. }
  35. return processedData
  36. }
  37. module.exports.finalReport = async function (reports, program) {
  38. if (program.output === undefined) {
  39. return
  40. }
  41. if (program.joinReports) {
  42. var out = {}
  43. for (var report of reports) {
  44. log.action('compiling', report.name)
  45. out[report.name] = report.contents
  46. }
  47. if (program.output === '-') {
  48. log.raw(JSON.stringify(out, null, 2))
  49. } else {
  50. // fs.ensureDirSync(path.dirname(program.output))
  51. // fs.copySync(sourceFile, outDir)
  52. let outPath = program.output + '.json'
  53. log.action('saving', outPath)
  54. fs.writeFileSync(outPath, JSON.stringify(out, null, 2), 'utf8')
  55. }
  56. } else {
  57. fs.ensureDirSync(program.output)
  58. for (let report of reports) {
  59. let outPath = path.join(program.output, report.name + '.json')
  60. log.action('saving', outPath)
  61. if (program.output === '-') {
  62. console.log(JSON.stringify(report.contents))
  63. } else {
  64. fs.writeFileSync(outPath, JSON.stringify(report.contents), 'utf8')
  65. }
  66. }
  67. }
  68. }