UNPKG

nope-js-node

Version:

NoPE Runtime for Nodejs. For Browser-Support please use nope-browser

78 lines (77 loc) 3.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.recordCPUProfile = exports.generateLogfilePath = exports.DEFAULT_LOG_LOCATION = exports.CURRENT_DATE = void 0; const path_1 = require("path"); const stringMethods_1 = require("../helpers/stringMethods"); const index_browser_1 = require("../index.browser"); const index_nodejs_1 = require("../index.nodejs"); exports.CURRENT_DATE = _parsableISOString(); exports.DEFAULT_LOG_LOCATION = (0, path_1.join)(process.cwd(), "logs"); const DEFAULT_FILE = (0, path_1.join)(exports.DEFAULT_LOG_LOCATION, "cpu_profile_" + exports.CURRENT_DATE + ".cpuprofile"); const logger = (0, index_browser_1.getNopeLogger)("CPU-Profiler"); function _parsableISOString(date = new Date()) { let isoString = date.toISOString(); isoString = (0, stringMethods_1.replaceAll)(isoString, ":", "-"); isoString = (0, stringMethods_1.replaceAll)(isoString, ".", "-"); return isoString; } /** * Generates a Log-File Path based on the given name with the following format: * /logs/{name}_{date}.log * * @export * @param {string} name Name of the File. * @return {string} * @backend **Only in Nodejs available** */ function generateLogfilePath(name) { return (0, path_1.join)(exports.DEFAULT_LOG_LOCATION, name + "_" + _parsableISOString() + ".cpuprofile"); } exports.generateLogfilePath = generateLogfilePath; function recordCPUProfile(pathToFile = DEFAULT_FILE) { const title = "cpu-profile"; const nodeVersion = process.version.match(/^v(\d+\.\d+)/)[1]; const major = nodeVersion.split(".")[0]; if (parseInt(major) >= 19) { const v8Profiler = require("v8-profiler-next"); // set generateType 1 to generate new format for cpuprofile // to be compatible with cpuprofile parsing in vscode. v8Profiler.setGenerateType(1); // ex. 5 mins cpu profile v8Profiler.startProfiling(title, true); let stopped = false; const stopProfiling = async () => { if (stopped) { return; } stopped = true; const profile = v8Profiler.stopProfiling(title); const promise = new Promise((resolve, reject) => { profile.export(function (error, result) { if (error) { reject(error); } resolve(result); }); }); const result = await promise; // if it doesn't have the extension .cpuprofile then // chrome's profiler tool won't like it. // examine the profile: // Navigate to chrome://inspect // Click Open dedicated DevTools for Node // Select the profiler tab // Load your file await (0, index_nodejs_1.createFile)(pathToFile, result); logger.info("Please open google chrome and open chrome://inspect and load the file", pathToFile); // Clear the Profile. profile.delete(); }; return stopProfiling; } logger.warn("Logging not enabled for the current node version. "); return async () => { // Placeholder. }; } exports.recordCPUProfile = recordCPUProfile;