Skip to content

Commit af6ce2c

Browse files
committed
fix: Incompatible with module.registerHooks
1 parent d6e7492 commit af6ce2c

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

hook.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const { builtinModules } = require('module')
88
const specifiers = new Map()
99
const isWin = process.platform === 'win32'
1010
let experimentalPatchInternals = false
11+
const { readFileSync } = require('fs')
1112

1213
// FIXME: Typescript extensions are added temporarily until we find a better
1314
// way of supporting arbitrary extensions
@@ -466,7 +467,17 @@ register(${JSON.stringify(realUrl)}, _, set, get, ${JSON.stringify(specifiers.ge
466467
}
467468
}
468469

469-
return parentLoad(url, context, parentLoad)
470+
const parentResult = await parentLoad(url, context, parentLoad)
471+
472+
// Prevent returning a nullish value for the source if a CJS module is loaded.
473+
// The reason for this is that Node.js will otherwise crash if the synchronous
474+
// module customization hooks are used: https://github.com/nodejs/node/issues/57327
475+
// The Node.js documentation also mentions that returning nullish values will no longer be supported in future.
476+
if (parentResult.format === 'commonjs' && (parentResult.source === null || parentResult.source === undefined)) {
477+
parentResult.source = readFileSync(fileURLToPath(url), 'utf8')
478+
}
479+
480+
return parentResult
470481
}
471482

472483
if (NODE_MAJOR >= 17 || (NODE_MAJOR === 16 && NODE_MINOR >= 12)) {
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { register, registerHooks } from 'module'
2+
import Hook from '../../index.js'
3+
import { strictEqual } from 'assert'
4+
5+
register('../../hook.mjs', import.meta.url)
6+
7+
registerHooks({
8+
load: (url, context, defaultLoad) => {
9+
return defaultLoad(url, context)
10+
}
11+
})
12+
13+
let bar
14+
15+
Hook((exports, name) => {
16+
if (name.match(/circular-b.mjs/)) {
17+
bar = exports.bar
18+
}
19+
})
20+
21+
await import('../fixtures/circular-b.mjs')
22+
23+
strictEqual(bar, 2)

0 commit comments

Comments
 (0)