playwright-performance
Version:
Playwright plugin for analyzing test flow performance
117 lines (116 loc) • 3.61 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileWriter = void 0;
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const app_root_path_1 = __importDefault(require("app-root-path"));
const logger_1 = __importDefault(require("./logger"));
class FileWriter {
constructor() {
this.lock = Promise.resolve();
this._logger = new logger_1.default(false);
}
static getInstance() {
if (!FileWriter.instance) {
FileWriter.instance = new FileWriter();
}
return FileWriter.instance;
}
async readAllLines(path) {
await this.lock;
let data = "";
try {
this.lock = this.lockFile();
data = await fs_1.promises.readFile(path, "utf-8");
}
catch (err) {
this._logger.error(`An error occurred while reading file ${path}: ${err}`, true);
}
finally {
await this.unlockFile();
}
const stringArray = data.split("\n");
return stringArray;
}
async writeToFile(path, data) {
await this.lock;
try {
this.lock = this.lockFile();
await fs_1.promises.writeFile(path, data);
}
catch (err) {
this._logger.error(`An error occurred while writing file ${path}: ${err}`, true);
}
finally {
await this.unlockFile();
}
}
async appendLineToFile(path, data) {
await this.lock;
try {
this.lock = this.lockFile();
await fs_1.promises.appendFile(path, data);
}
catch (err) {
this._logger.error(`An error occurred while appending file ${path}: ${err}`, true);
}
finally {
await this.unlockFile();
}
}
getFilePath(resultsDir, fileName) {
return path_1.default.join(resultsDir, fileName);
}
async createResultsDirIfNotExist(resultsPath) {
let npath = "";
const root = app_root_path_1.default.path;
let isNotLegal = true;
if (resultsPath) {
isNotLegal = /[*"\[\]:;|,]/g.test(resultsPath);
npath = path_1.default.normalize(resultsPath);
}
const resultsDir = npath == undefined || npath == "" || isNotLegal ? "performance-results" : npath;
if (!root) {
this._logger.error("Can't get root folder", true);
return "";
}
const dirPath = path_1.default.join(root, resultsDir);
const isFileExists = await this.isFileExist(dirPath);
if (!isFileExists) {
await this.makeDir(dirPath);
}
return dirPath;
}
async makeDir(dirPath) {
try {
await fs_1.promises.mkdir(dirPath, { recursive: true });
}
catch (err) {
this._logger.error(`Can't create dir: ${dirPath}: ${err}`, true);
}
}
async isFileExist(dirPath) {
let isExists = false;
try {
await fs_1.promises.access(dirPath);
isExists = true;
}
finally {
return isExists;
}
}
async lockFile() {
await this.lock;
this.lock = new Promise((resolve) => {
setImmediate(resolve);
});
}
async unlockFile() {
await this.lock;
this.lock = Promise.resolve();
}
}
exports.FileWriter = FileWriter;