diff --git a/index.js b/index.js index d7f870d..9189e97 100644 --- a/index.js +++ b/index.js @@ -21,7 +21,7 @@ const hook = createHook({ asyncResources.set(asyncId, { type, - resource, + resourceRef: new WeakRef(resource), stacks }) }, @@ -36,7 +36,15 @@ export default function whyIsNodeRunning (logger = console) { hook.disable() const activeAsyncResources = Array.from(asyncResources.values()) - .filter(({ resource }) => resource.hasRef?.() ?? true) + .filter(({ resourceRef }) => { + const resource = resourceRef.deref() + + if (resource === undefined) { + return false + } + + return resource.hasRef?.() ?? true + }) logger.error(`There are ${activeAsyncResources.length} handle(s) keeping the process running.`) @@ -47,7 +55,7 @@ export default function whyIsNodeRunning (logger = console) { function printStacks (asyncResource, logger) { const stacks = asyncResource.stacks.filter((stack) => { - const fileName = stack.getFileName() + const fileName = stack.fileName return fileName !== null && !fileName.startsWith('node:') }) @@ -66,8 +74,8 @@ function printStacks (asyncResource, logger) { const padding = ' '.repeat(maxLength - location.length) try { - const lines = readFileSync(normalizeFilePath(stack.getFileName()), 'utf-8').split(/\n|\r\n/) - const line = lines[stack.getLineNumber() - 1].trim() + const lines = readFileSync(normalizeFilePath(stack.fileName), 'utf-8').split(/\n|\r\n/) + const line = lines[stack.lineNumber - 1].trim() logger.error(`${location}${padding} - ${line}`) } catch (e) { @@ -77,8 +85,8 @@ function printStacks (asyncResource, logger) { } function formatLocation (stack) { - const filePath = formatFilePath(stack.getFileName()) - return `${filePath}:${stack.getLineNumber()}` + const filePath = formatFilePath(stack.fileName) + return `${filePath}:${stack.lineNumber}` } function formatFilePath (filePath) { @@ -92,12 +100,19 @@ function normalizeFilePath (filePath) { return filePath.startsWith('file://') ? fileURLToPath(filePath) : filePath } +function prepareStackTrace(error, stackTraces) { + return stackTraces.map(stack => ({ + lineNumber: stack.getLineNumber(), + fileName: stack.getFileName() + })) +} + // See: https://v8.dev/docs/stack-trace-api function captureStackTraces () { const target = {} const original = Error.prepareStackTrace - Error.prepareStackTrace = (error, stackTraces) => stackTraces + Error.prepareStackTrace = prepareStackTrace Error.captureStackTrace(target, captureStackTraces) const capturedTraces = target.stack