Skip to content

Commit 73e5743

Browse files
committed
module: implement Symbol.dispose in ModuleHooks
This change implements the `Symbol.dispose` key in the `ModuleHooks` class as an alias for deregister. This makes `registerHooks` work with the `using` keyword. Fixes: #63846 Signed-off-by: Remco Haszing<remcohaszing@gmail.com>
1 parent 3f42cfa commit 73e5743

3 files changed

Lines changed: 36 additions & 4 deletions

File tree

doc/api/module.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,7 @@ changes:
245245
* `deregister()` {Function} Remove the registered hooks so that they are no
246246
longer called. Hooks are otherwise retained for the lifetime of the running
247247
process.
248+
* `[Symbol.dispose]` {Function} The same as `deregister`.
248249
249250
Register [hooks][] that customize Node.js module resolution and loading behavior.
250251
See [Customization hooks][]. The returned object can be used to

lib/internal/modules/customization_hooks.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ const {
99
StringPrototypeSlice,
1010
StringPrototypeStartsWith,
1111
Symbol,
12+
SymbolDispose,
1213
} = primordials;
1314
const {
1415
isAnyArrayBuffer,
@@ -83,10 +84,7 @@ class ModuleHooks {
8384

8485
ObjectFreeze(this);
8586
}
86-
// TODO(joyeecheung): we may want methods that allow disabling/enabling temporarily
87-
// which just sets the item in the array to undefined temporarily.
88-
// TODO(joyeecheung): this can be the [Symbol.dispose] implementation to pair with
89-
// `using` when the explicit resource management proposal is shipped by V8.
87+
9088
/**
9189
* Deregister the hook instance.
9290
*/
@@ -101,6 +99,13 @@ class ModuleHooks {
10199
ArrayPrototypeSplice(loadHooks, index, 1);
102100
}
103101
}
102+
103+
/**
104+
* Deregister the hook instance.
105+
*/
106+
[SymbolDispose]() {
107+
this.deregister();
108+
}
104109
};
105110

106111
/**
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const assert = require('assert');
5+
const { registerHooks } = require('module');
6+
7+
// Test that using syntax works.
8+
{
9+
// eslint-disable-next-line no-unused-vars
10+
using hook = registerHooks({
11+
load: common.mustCall((url, context, nextLoad) => {
12+
const result = nextLoad(url, context);
13+
assert.strictEqual(result.source, '');
14+
return {
15+
source: 'export const hello = "world"',
16+
};
17+
}),
18+
});
19+
20+
const mod = require('../fixtures/empty.js');
21+
assert.strictEqual(mod.hello, 'world');
22+
}
23+
24+
delete require.cache[require.resolve('../fixtures/empty.js')];
25+
const mod = require('../fixtures/empty.js');
26+
assert.deepStrictEqual(mod, {});

0 commit comments

Comments
 (0)