NodeJS `isolated-vm`: How to reference a function inside the isolate

2.4k Views Asked by At

The following code:

const ivm = require('isolated-vm');

const isolate = new ivm.Isolate();
const context = isolate.createContextSync();

context.setSync('log', new ivm.Callback(x => console.log(x)));
// receives a function and triggers it on an interval
context.setSync('onEvent', new ivm.Callback((handler) => {
   setInterval(() => handler(), 1000)
}));

const script = isolate.compileScriptSync(`onEvent(() => log('hello'))`);
script.runSync(context);

Produces the following error:

function '() => log('hello')' could not be cloned

I understand why a function cannot be copied from one isolate to another, But I would like to get back a reference to that callback so I can trigger it later with ref.apply(..).

How can I get a reference to a function from inside the isolate?

(without exposing the ivm module itself to the isolate which is unsafe)

1

There are 1 best solutions below

1
On

I use

context.evalClosureSync(`
  globalThis.console = {
    log: $0
  }
`,
[
   (...args) => console.log(...args)
]);

Is this code solving your issue?