node/lib/internal/profiler.js
Joyee Cheung ab70c96a79
src: refactor coverage connection
- Refactor the C++ class to be resuable for other types of profiles
- Move the try-catch block around coverage collection callback
  to be inside the callback to silence potential JSON or write
  errors.
- Use Function::Call instead of MakeCallback to call the coverage
  message callback since it does not actually need async hook
  handling. This way we no longer needs to disable the async
  hooks when writing the coverage results.
- Renames `lib/internal/coverage-gen/with_profiler.js` to
  `lib/internal/profiler.js` because it is now the only way
  to generate coverage.

PR-URL: https://github.com/nodejs/node/pull/26513
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Ben Coe <bencoe@gmail.com>
2019-03-30 14:44:57 +01:00

44 lines
1.0 KiB
JavaScript

'use strict';
// Implements coverage collection exposed by the `NODE_V8_COVERAGE`
// environment variable which can also be used in the user land.
let coverageDirectory;
function writeCoverage() {
const { join } = require('path');
const { mkdirSync, writeFileSync } = require('fs');
const { threadId } = require('internal/worker');
const filename = `coverage-${process.pid}-${Date.now()}-${threadId}.json`;
try {
mkdirSync(coverageDirectory, { recursive: true });
} catch (err) {
if (err.code !== 'EEXIST') {
console.error(err);
return;
}
}
const target = join(coverageDirectory, filename);
internalBinding('profiler').endCoverage((msg) => {
try {
const coverageInfo = JSON.parse(msg).result;
if (coverageInfo) {
writeFileSync(target, JSON.stringify(coverageInfo));
}
} catch (err) {
console.error(err);
}
});
}
function setCoverageDirectory(dir) {
coverageDirectory = dir;
}
module.exports = {
writeCoverage,
setCoverageDirectory
};