Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion hook.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
const { URL, fileURLToPath } = require('url')
const { inspect } = require('util')
const { builtinModules } = require('module')
const { readFileSync } = require('fs')
const specifiers = new Map()
const isWin = process.platform === 'win32'
let experimentalPatchInternals = false
Expand Down Expand Up @@ -466,7 +467,17 @@ register(${JSON.stringify(realUrl)}, _, set, get, ${JSON.stringify(specifiers.ge
}
}

return parentLoad(url, context, parentLoad)
const parentResult = await parentLoad(url, context, parentLoad)

// Prevent returning a nullish value for the source if a CJS module is loaded.
// The reason for this is that Node.js will otherwise crash if the synchronous
// module customization hooks are used: https://github.com/nodejs/node/issues/57327
// The Node.js documentation also mentions that returning nullish values will no longer be supported in future.
if (parentResult.format === 'commonjs' && !parentResult.source) {
parentResult.source = readFileSync(fileURLToPath(url), 'utf8')
}

return parentResult
}

if (NODE_MAJOR >= 17 || (NODE_MAJOR === 16 && NODE_MINOR >= 12)) {
Expand Down
23 changes: 23 additions & 0 deletions test/register/v24-register-hooks.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { register, registerHooks } from 'module'
import Hook from '../../index.js'
import { strictEqual } from 'assert'

register('../../hook.mjs', import.meta.url)

registerHooks({
load: (url, context, defaultLoad) => {
return defaultLoad(url, context)
}
})

let bar

Hook((exports, name) => {
if (name.match(/circular-b.mjs/)) {
bar = exports.bar
}
})

await import('../fixtures/circular-b.mjs')

strictEqual(bar, 2)
Loading