From 82348bd311e2b89b99ad52d2d0a2526617e297e6 Mon Sep 17 00:00:00 2001 From: Jithil P Ponnan Date: Thu, 9 Nov 2023 20:44:56 +1100 Subject: [PATCH] lib: fix assert shows diff messages in ESM and CJS This PR addresses issue #50593, which was caused by the design in the ESM loader. The ESM loader was modifying the file path and replacing the 'file' property with the file proto in the stack trace. This, in turn, led to unhandled exceptions when the assert module attempted to open the file to display erroneous code. The changes in this PR resolve this issue by handling the file path correctly, ensuring that the remaining message formatting code can execute as expected. --- lib/assert.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/assert.js b/lib/assert.js index b7d7a3da01d520..7230827aaa7a4b 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -296,7 +296,7 @@ function getErrMessage(message, fn) { overrideStackTrace.set(err, (_, stack) => stack); const call = err.stack[0]; - const filename = call.getFileName(); + let filename = call.getFileName(); const line = call.getLineNumber() - 1; let column = call.getColumnNumber() - 1; let identifier; @@ -330,6 +330,14 @@ function getErrMessage(message, fn) { const { StringDecoder } = require('string_decoder'); decoder = new StringDecoder('utf8'); } + + // ESM file prop is a file proto. Convert that to path. + // This ensure opensync will not throw ENOENT for ESM files. + const fileProtoPrefix = 'file://'; + if (StringPrototypeStartsWith(filename, fileProtoPrefix)) { + filename = StringPrototypeReplace(filename, fileProtoPrefix, ''); + } + fd = openSync(filename, 'r', 0o666); // Reset column and message. ({ 0: column, 1: message } = getCode(fd, line, column));