I’m trying to use node.js’s vm module for an automated test I’m writing, as far as I can tell, it doesn’t build an environment with the global
variable:
$ node -p 'const vm = require("node:vm"); const context = {}; vm.runInNewContext("global.foo=5;", context); console.log(context);'
evalmachine.<anonymous>:1
global.foo=5;
^
ReferenceError: global is not defined
It does seem to come with globalThis
, though:
$ node -p 'const vm = require("node:vm"); const context = {}; vm.runInNewContext("globalThis.foo=5;", context); console.log(context);'
{ foo: 5 }
undefined
I’m not sure why or even how it’s missing global
, but how do I create a vm context with it?
Note: I’m going to answer my question but I’m not confident it’s a good solution. Let me know if it can be improved.