Skip to content

Commit

Permalink
Use a WeakRef to store the resource
Browse files Browse the repository at this point in the history
Closes #84
  • Loading branch information
betalb committed Jan 7, 2025
1 parent 01906a9 commit 184c4ec
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const hook = createHook({

asyncResources.set(asyncId, {
type,
resource,
resourceRef: new WeakRef(resource),
stacks
})
},
Expand All @@ -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.`)

Expand All @@ -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:')
})

Expand All @@ -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) {
Expand All @@ -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) {
Expand All @@ -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
Expand Down

0 comments on commit 184c4ec

Please sign in to comment.