lib/reporters/json.js

const file = require('../file.js').file;

/**
 * @module pete/lib/reporters/json
 */
module.exports = createJSON;

/**
 * JSON
 *
 * @external JSON
 * @see {@link https://www.json.org/}
 */

/**
 * Create and return report function that will output reports in JSON format.
 *
 * @see {@link external:JSON}
 * @alias module:pete/lib/reporters/json
 * @param {object} [options]
 * @param {object} [options.out]        path to file that should be created
 * @param {object} [options.callback]   to call once on `out` stream `close` event
 * @return {module:pete/lib/getReporters~report}
 */
function createJSON (options) {
	var index = 0;
	var out = (options && options.out) || process.stdout;
	var callback = (options && options.callback) || null;

	if (typeof out === 'string') {
		try {
			out = file(out, true);
		}
		catch (e) {
			console.error(e);
			out = process.stderr;
		}
	}

	if (typeof callback === 'function') {
		out.once('close', options.callback);
	}

	return function json (err, report) {
		if (index < 0) {
			console.error(new Error('JSON reporter called after it was closed'));
			return;
		}

		if (index === 0) {
			out.write('[');
		}

		if (!err && !report) {
			out.end(']\n');
			index = -1;
			return;
		}

		if (index > 0) {
			out.write(',');
		}

		index++;

		out.write(JSON.stringify({
			error: (err && err.stack) || null,
			report
		}, null, '\t'));
	};
}