UNPKG

playwright-performance-reporter

Version:

Measure and publish performance metrics from browser dev-tools when running playwright

93 lines (92 loc) 2.34 kB
import path from 'node:path'; import fs from 'node:fs'; import JSONStream from 'JSONStream'; import { Logger, } from '../../helpers/index.js'; /** * Write JSON chunks in an array of entries */ export class JsonChunkPresenter { /** * Locator where to store the output */ filePath; /** * Status whether writer is usable */ isClosed = false; /** * File writer */ fileStream; /** * JSON chunk writer */ jsonStream = JSONStream.stringify('[', ',', ']'); constructor(options) { this.filePath = path.join(options.outputDir, options.outputFile); this.fileStream = fs.createWriteStream(this.filePath, { flags: 'w' }); this.jsonStream.pipe(this.fileStream); } /** * Create new entry of an object, that is serializable. * * @param content */ async write(content) { if (this.isClosed) { return false; } return new Promise(resolve => { try { // @ts-expect-error: writer is able to handle more types if (this.jsonStream.write(content)) { resolve(true); } else { this.fileStream?.once('drain', () => { resolve(true); }); } } catch (error) { Logger.error(String(error)); resolve(false); } }); } /** * Finish json stream */ async close() { this.isClosed = true; return new Promise(resolve => { try { this.jsonStream.end(); this.fileStream?.end(); this.fileStream?.once('finish', () => { resolve(true); }); } catch (error) { Logger.error(String(error)); resolve(false); } }); } /** * Delete created file */ async delete() { try { await this.close(); } catch { return false; } if (this.filePath) { fs.rmSync(this.filePath, { maxRetries: 5, retryDelay: 500 }); return true; } return false; } }