vm.Module.link() called on an already-linked module
Production Risk
Low — typically only affects sandboxing or test runner infrastructure.
Thrown when vm.Module.link() is called on a module instance that has already been successfully linked. A vm.Module can only progress through its lifecycle (unlinked → linking → linked → evaluated) in one direction; calling link() again after it has already been linked is not allowed.
- 1Calling mod.link() a second time on the same module instance
- 2Sharing a module instance across multiple evaluation cycles and re-linking it
- 3A logic error in an async linking loop that processes the same module twice
Triggered when link() is invoked on a vm.Module whose status is already "linked" or "evaluated".
import vm from 'node:vm';
const mod = new vm.SourceTextModule('export const x = 1;');
await mod.link(() => {});
await mod.link(() => {}); // second call throwsexpected output
Error [ERR_VM_MODULE_ALREADY_LINKED]: Module has already been linked
Fix 1
Check module status before linking
WHEN When you are unsure whether a module has already been linked
if (mod.status === 'unlinked') {
await mod.link(linker);
}Why this works
Guarding on mod.status prevents redundant link() calls.
Fix 2
Create a fresh vm.Module instance for each evaluation
WHEN When you need to re-evaluate the same source
async function runModule(src) {
const mod = new vm.SourceTextModule(src);
await mod.link(linker);
await mod.evaluate();
return mod.namespace;
}Why this works
Creating a new instance resets the lifecycle, avoiding the already-linked error.
import vm from 'node:vm';
const mod = new vm.SourceTextModule('export const x = 1;');
await mod.link(() => {});
await mod.link(() => {}); // second call throws // this triggers ERR_VM_MODULE_ALREADY_LINKEDtry {
// operation that may throw ERR_VM_MODULE_ALREADY_LINKED
riskyOperation()
} catch (err) {
if (err.code === 'ERR_VM_MODULE_ALREADY_LINKED') {
console.error('ERR_VM_MODULE_ALREADY_LINKED:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_vm_module_already_linked(...args) {
// validate args here
return performOperation(...args)
}✕ Reuse vm.Module instances across multiple evaluation runs
Module instances are stateful and cannot be re-linked once they advance past the "unlinked" state.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev