Skip to content

Commit

Permalink
Support tracking requires
Browse files Browse the repository at this point in the history
Signed-off-by: Darshan Sen <[email protected]>
  • Loading branch information
RaisinTen committed Apr 25, 2024
1 parent ce5ec58 commit 21554e0
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
23 changes: 22 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,25 @@ class TraceEvents {
}
}

module.exports = { TraceEvents };
// Monkey patching require().
// Refs: https://stackoverflow.com/a/42883538
const Module = require('module');
const originalRequire = Module.prototype.require;

function trackRequires(shouldTrackRequires) {
if (shouldTrackRequires) {
Module.prototype.require = function () {
performance.mark(`require("${arguments[0]}")`);
const ret = originalRequire.apply(this, arguments);
performance.measure(`require("${arguments[0]}")`, `require("${arguments[0]}")`);
return ret;
};
} else {
Module.prototype.require = originalRequire;
}
}

module.exports = {
TraceEvents,
trackRequires,
};
29 changes: 28 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { ok } = require("node:assert");
const { TraceEvents } = require("..");
const { TraceEvents, trackRequires } = require("..");
const { after, before, describe, test } = require("node:test");
const { performance } = require("node:perf_hooks");

Expand Down Expand Up @@ -65,3 +65,30 @@ describe("interleaved events", async () => {
traceEvents.destroy();
});
});

describe("track requires", async () => {
let traceEvents;

await before(async () => {
traceEvents = new TraceEvents();
console.log(traceEvents);
trackRequires(true);
require("node:tls");
trackRequires(false);
require("node:net");

return new Promise((resolve, reject) => setImmediate(resolve));
});

test("find events", () => {
const events = traceEvents.getEvents();
const requireTls = events.find((element) => element.name === `require("node:tls")`);
ok(requireTls);
const requireNet = events.find((element) => element.name === `require("node:net")`);
ok(!requireNet);
});

after(() => {
traceEvents.destroy();
});
});

0 comments on commit 21554e0

Please sign in to comment.