Home Reference Source Test

lib/reporters/json.js

  1. var util = require('util');
  2. var path = require('path');
  3. var chalk = require('chalk');
  4. var BaseReporter = require('./base');
  5.  
  6. /**
  7. *
  8. */
  9. class JSONReporter extends BaseReporter {
  10. /**
  11. * A JSON reporter, which displays both file and line information for
  12. * each given match.
  13. *
  14. * @constructor
  15. *
  16. * @param {Inspector} inspector Instance on which to register its listeners
  17. * @param {object} opts Options to set for the reporter
  18. */
  19. constructor(inspector, opts) {
  20. opts = opts || {};
  21. super(inspector, opts);
  22.  
  23. var enabled = chalk.enabled;
  24.  
  25. inspector.on('start', () => {
  26. chalk.enabled = false;
  27. this._writableStream.write('[');
  28. });
  29.  
  30. inspector.on('end', () => {
  31. chalk.enabled = enabled;
  32. this._writableStream.write(']\n');
  33. });
  34. }
  35.  
  36. /**
  37. * Returns the string output to print for the given reporter. The formatted
  38. * JSON string contains the number of instances associated with the match and
  39. * the files and lines involved.
  40. *
  41. * @private
  42. *
  43. * @param {Match} match The inspector match to output
  44. * @returns {string} The formatted output
  45. */
  46. _getOutput(match) {
  47. var output = (this._found > 1) ? ',\n' : '';
  48.  
  49. output += JSON.stringify({
  50. id: match.hash,
  51. instances: match.instances.map(instance => {
  52. return {
  53. path: this._getRelativePath(instance.filename),
  54. lines: [instance.start.line, instance.end.line],
  55. code: this._getLines(instance)
  56. };
  57. })
  58. });
  59.  
  60. return output;
  61. }
  62. }
  63.  
  64. module.exports = JSONReporter;