diff --git a/README.md b/README.md index d648551..b849b6e 100644 --- a/README.md +++ b/README.md @@ -64,20 +64,20 @@ Here's the output: There are 4 handle(s) keeping the process running # Timeout -/path/to/project/example.js:6 - setInterval(() => {}, 1000) -/path/to/project/example.js:10 - startServer() +example.js:6 - setInterval(() => {}, 1000) +example.js:10 - startServer() # TCPSERVERWRAP -/path/to/project/example.js:7 - server.listen(0) -/path/to/project/example.js:10 - startServer() +example.js:7 - server.listen(0) +example.js:10 - startServer() # Timeout -/path/to/project/example.js:6 - setInterval(() => {}, 1000) -/path/to/project/example.js:11 - startServer() +example.js:6 - setInterval(() => {}, 1000) +example.js:11 - startServer() # TCPSERVERWRAP -/path/to/project/example.js:7 - server.listen(0) -/path/to/project/example.js:11 - startServer() +example.js:7 - server.listen(0) +example.js:11 - startServer() ``` ## Usage (as a CLI) diff --git a/index.js b/index.js index 1c8e700..40fb6b8 100644 --- a/index.js +++ b/index.js @@ -51,13 +51,13 @@ export default function whyIsNodeRunning (logger) { } else { var padding = '' stacks.forEach(function (s) { - var pad = (normalizeFileName(s.getFileName()) + ':' + s.getLineNumber()).replace(/./g, ' ') + var pad = formatLocation(s).replace(/./g, ' ') if (pad.length > padding.length) padding = pad }) stacks.forEach(function (s) { - var prefix = normalizeFileName(s.getFileName()) + ':' + s.getLineNumber() + var prefix = formatLocation(s) try { - var src = fs.readFileSync(normalizeFileName(s.getFileName()), 'utf-8').split(/\n|\r\n/) + var src = fs.readFileSync(normalizeFilePath(s.getFileName()), 'utf-8').split(/\n|\r\n/) logger.error(prefix + padding.slice(prefix.length) + ' - ' + src[s.getLineNumber() - 1].trim()) } catch (e) { logger.error(prefix + padding.slice(prefix.length)) @@ -67,6 +67,24 @@ export default function whyIsNodeRunning (logger) { } } -function normalizeFileName(fileName) { - return fileName.startsWith('file://') ? fileURLToPath(fileName) : fileName +function formatLocation (stack) { + const filePath = formatFilePath(stack.getFileName()) + return `${filePath}:${stack.getLineNumber()}` +} + +function formatFilePath (filePath) { + const absolutePath = normalizeFilePath(filePath) + const relativePath = path.relative(process.cwd(), absolutePath) + + // If the file is outside the current working directory, return the absolute path. + return relativePath.startsWith('..') ? absolutePath : relativePath +} + +function normalizeFilePath (filePath) { + // Convert file:// URLs to file paths. + if (filePath.startsWith('file://')) { + return fileURLToPath(filePath) + } + + return filePath }