Skip to content

Instantly share code, notes, and snippets.

@IdrisAkintobi
Forked from amirilovic/take-memory-snapshot.ts
Last active April 17, 2025 19:21
Show Gist options
  • Save IdrisAkintobi/a58452c0f4e3b0ec05e001df9f669709 to your computer and use it in GitHub Desktop.
Save IdrisAkintobi/a58452c0f4e3b0ec05e001df9f669709 to your computer and use it in GitHub Desktop.
A script that save heap snapshot from a nodejs process in debug mode to a file
import fs from "fs";
import { WebSocket } from "ws";
async function getWebSocketDebuggerUrl() {
const res = await fetch("http://localhost:9229/json");
const data = await res.json();
return data[0].webSocketDebuggerUrl;
}
let ws: WebSocket;
async function takeHeapSnapshot() {
try {
process.on("uncaughtException", (err) => {
console.error(err);
process.exit(1);
});
// Create temp file
const fileName = "profile-" + Date.now() + ".heapsnapshot";
// Get the WebSocket URL
const webSocketDebuggerUrl = await getWebSocketDebuggerUrl();
await new Promise<void>((resolve) => {
// use WebSocket to connect to the target process
ws = new WebSocket(webSocketDebuggerUrl);
let loggedWriteStatus: boolean | undefined = undefined;
// listen for addChunk events
ws.on("message", (data) => {
!loggedWriteStatus && console.log("Writing data to file...");
loggedWriteStatus ??= true;
const message = JSON.parse(data.toString());
if (message.method === "HeapProfiler.addHeapSnapshotChunk") {
fs.appendFileSync(fileName, message.params.chunk);
} else if (message.id === 2) {
resolve();
}
});
ws.on("error", console.error);
ws.on("open", function open() {
console.log("connected to debugger websocket");
// Send message to take heapSnapshot
console.log("Taking HeapSnapshot...");
ws.send(
JSON.stringify({
id: 2,
method: "HeapProfiler.takeHeapSnapshot",
})
);
});
});
console.log("Heap Snapshot captured!");
} catch (err) {
console.error("An error occurred:", err);
} finally {
if (ws) {
ws.close();
}
}
}
takeHeapSnapshot();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment